<commit_before> /*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: accfootnote.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 02:47:24 $
 *
 *  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
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _VOS_MUTEX_HXX_ //autogen
#include <vos/mutex.hxx>
#endif

#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_
#include <com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_
#include <com/sun/star/accessibility/AccessibleStateType.hpp>
#endif

#ifndef _UTL_ACCESSIBLESTATESETHELPER_HXX_
#include <unotools/accessiblestatesethelper.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif
#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif
#ifndef _SV_SVAPP_HXX //autogen
#include <vcl/svapp.hxx>
#endif
#ifndef _FTNFRM_HXX
#include <ftnfrm.hxx>
#endif
#ifndef _FMTFTN_HXX //autogen
#include <fmtftn.hxx>
#endif
#ifndef _TXTFTN_HXX //autogen
#include <txtftn.hxx>
#endif
#ifndef _VIEWSH_HXX
#include <viewsh.hxx>
#endif
#ifndef _PAGEFRM_HXX
//#include <pagefrm.hxx>
#endif
#ifndef _PAGEDESC_HXX
//#include <pagedesc.hxx>
#endif

#ifndef _FLDBAS_HXX
//#include <fldbas.hxx>
#endif
#ifndef _ACCMAP_HXX
#include <accmap.hxx>
#endif
#ifndef _ACCFOOTNOTE_HXX
#include "accfootnote.hxx"
#endif
#ifndef _ACCESS_HRC
#include "access.hrc"
#endif

using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::accessibility;
using namespace ::rtl;

const sal_Char sServiceNameFootnote[] = "com.sun.star.text.AccessibleFootnoteView";
const sal_Char sServiceNameEndnote[] = "com.sun.star.text.AccessibleEndnoteView";
const sal_Char sImplementationNameFootnote[] = "com.sun.star.comp.Writer.SwAccessibleFootnoteView";
const sal_Char sImplementationNameEndnote[] = "com.sun.star.comp.Writer.SwAccessibleEndnoteView";

SwAccessibleFootnote::SwAccessibleFootnote(
        SwAccessibleMap *pMap,
        sal_Bool bIsEndnote,
        sal_Int32 nFootEndNote,
        const SwFtnFrm *pFtnFrm ) :
    SwAccessibleContext( pMap,
        bIsEndnote ? AccessibleRole::END_NOTE : AccessibleRole::FOOTNOTE,
        pFtnFrm )
{
    vos::OGuard aGuard(Application::GetSolarMutex());

    sal_uInt16 nResId = bIsEndnote ? STR_ACCESS_ENDNOTE_NAME
                                   : STR_ACCESS_FOOTNOTE_NAME;
    OUString sArg( OUString::valueOf( nFootEndNote ) );
    SetName( GetResource( nResId, &sArg ) );
}

SwAccessibleFootnote::~SwAccessibleFootnote()
{
}

OUString SAL_CALL SwAccessibleFootnote::getAccessibleDescription (void)
        throw (::com::sun::star::uno::RuntimeException)
{
    vos::OGuard aGuard(Application::GetSolarMutex());

    CHECK_FOR_DEFUNC( XAccessibleContext )

    sal_uInt16 nResId = AccessibleRole::END_NOTE == GetRole()
        ? STR_ACCESS_ENDNOTE_DESC
        : STR_ACCESS_FOOTNOTE_DESC ;

    OUString sArg;
    const SwTxtFtn *pTxtFtn =
        static_cast< const SwFtnFrm *>( GetFrm() )->GetAttr();
    if( pTxtFtn )
    {
        const SwDoc *pDoc = GetMap()->GetShell()->GetDoc();
        sArg = pTxtFtn->GetFtn().GetViewNumStr( *pDoc );
    }

    return GetResource( nResId, &sArg );
}

OUString SAL_CALL SwAccessibleFootnote::getImplementationName()
        throw( RuntimeException )
{
    if( AccessibleRole::END_NOTE == GetRole() )
        return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationNameEndnote));
    else
        return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationNameFootnote));
}

sal_Bool SAL_CALL SwAccessibleFootnote::supportsService(
        const ::rtl::OUString& sTestServiceName)
    throw (::com::sun::star::uno::RuntimeException)
{
    if( sTestServiceName.equalsAsciiL( sAccessibleServiceName,
                                       sizeof(sAccessibleServiceName)-1 ) )
        return sal_True;
    else if( AccessibleRole::END_NOTE == GetRole() )
        return sTestServiceName.equalsAsciiL( sServiceNameEndnote, sizeof(sServiceNameEndnote)-1 );
    else
        return sTestServiceName.equalsAsciiL( sServiceNameFootnote, sizeof(sServiceNameFootnote)-1 );

}

Sequence< OUString > SAL_CALL SwAccessibleFootnote::getSupportedServiceNames()
        throw( ::com::sun::star::uno::RuntimeException )
{
    Sequence< OUString > aRet(2);
    OUString* pArray = aRet.getArray();
    if( AccessibleRole::END_NOTE == GetRole() )
        pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceNameEndnote) );
    else
        pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceNameFootnote) );
    pArray[1] = OUString( RTL_CONSTASCII_USTRINGPARAM(sAccessibleServiceName) );
    return aRet;
}

Sequence< sal_Int8 > SAL_CALL SwAccessibleFootnote::getImplementationId()
        throw(RuntimeException)
{
    vos::OGuard aGuard(Application::GetSolarMutex());
    static Sequence< sal_Int8 > aId( 16 );
    static sal_Bool bInit = sal_False;
    if(!bInit)
    {
        rtl_createUuid( (sal_uInt8 *)(aId.getArray() ), 0, sal_True );
        bInit = sal_True;
    }
    return aId;
}

sal_Bool SwAccessibleFootnote::IsEndnote( const SwFtnFrm *pFtnFrm )
{
    const SwTxtFtn *pTxtFtn = pFtnFrm ->GetAttr();
    return pTxtFtn && pTxtFtn->GetFtn().IsEndNote() ;
}
<commit_msg>INTEGRATION: CWS writercorehandoff (1.9.1112); FILE MERGED 2005/09/13 12:53:23 tra 1.9.1112.3: RESYNC: (1.9-1.10); FILE MERGED 2005/06/07 14:13:00 fme 1.9.1112.2: #i50348# General cleanup - removed unused header files, functions, members, declarations etc. 2005/06/06 09:26:39 tra 1.9.1112.1: Unnecessary includes removed #i50348#<commit_after> /*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: accfootnote.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: hr $ $Date: 2006-08-14 15:42:40 $
 *
 *  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
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _VOS_MUTEX_HXX_ //autogen
#include <vos/mutex.hxx>
#endif

#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_
#include <com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_
#include <com/sun/star/accessibility/AccessibleStateType.hpp>
#endif

#ifndef _UTL_ACCESSIBLESTATESETHELPER_HXX_
#include <unotools/accessiblestatesethelper.hxx>
#endif
#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif
#ifndef _SV_SVAPP_HXX //autogen
#include <vcl/svapp.hxx>
#endif
#ifndef _FTNFRM_HXX
#include <ftnfrm.hxx>
#endif
#ifndef _FMTFTN_HXX //autogen
#include <fmtftn.hxx>
#endif
#ifndef _TXTFTN_HXX //autogen
#include <txtftn.hxx>
#endif
#ifndef _VIEWSH_HXX
#include <viewsh.hxx>
#endif
#ifndef _PAGEFRM_HXX
//#include <pagefrm.hxx>
#endif
#ifndef _PAGEDESC_HXX
//#include <pagedesc.hxx>
#endif

#ifndef _FLDBAS_HXX
//#include <fldbas.hxx>
#endif
#ifndef _ACCMAP_HXX
#include <accmap.hxx>
#endif
#ifndef _ACCFOOTNOTE_HXX
#include "accfootnote.hxx"
#endif
#ifndef _ACCESS_HRC
#include "access.hrc"
#endif

using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::accessibility;
using namespace ::rtl;

const sal_Char sServiceNameFootnote[] = "com.sun.star.text.AccessibleFootnoteView";
const sal_Char sServiceNameEndnote[] = "com.sun.star.text.AccessibleEndnoteView";
const sal_Char sImplementationNameFootnote[] = "com.sun.star.comp.Writer.SwAccessibleFootnoteView";
const sal_Char sImplementationNameEndnote[] = "com.sun.star.comp.Writer.SwAccessibleEndnoteView";

SwAccessibleFootnote::SwAccessibleFootnote(
        SwAccessibleMap *pMap,
        sal_Bool bIsEndnote,
        sal_Int32 nFootEndNote,
        const SwFtnFrm *pFtnFrm ) :
    SwAccessibleContext( pMap,
        bIsEndnote ? AccessibleRole::END_NOTE : AccessibleRole::FOOTNOTE,
        pFtnFrm )
{
    vos::OGuard aGuard(Application::GetSolarMutex());

    sal_uInt16 nResId = bIsEndnote ? STR_ACCESS_ENDNOTE_NAME
                                   : STR_ACCESS_FOOTNOTE_NAME;
    OUString sArg( OUString::valueOf( nFootEndNote ) );
    SetName( GetResource( nResId, &sArg ) );
}

SwAccessibleFootnote::~SwAccessibleFootnote()
{
}

OUString SAL_CALL SwAccessibleFootnote::getAccessibleDescription (void)
        throw (::com::sun::star::uno::RuntimeException)
{
    vos::OGuard aGuard(Application::GetSolarMutex());

    CHECK_FOR_DEFUNC( XAccessibleContext )

    sal_uInt16 nResId = AccessibleRole::END_NOTE == GetRole()
        ? STR_ACCESS_ENDNOTE_DESC
        : STR_ACCESS_FOOTNOTE_DESC ;

    OUString sArg;
    const SwTxtFtn *pTxtFtn =
        static_cast< const SwFtnFrm *>( GetFrm() )->GetAttr();
    if( pTxtFtn )
    {
        const SwDoc *pDoc = GetMap()->GetShell()->GetDoc();
        sArg = pTxtFtn->GetFtn().GetViewNumStr( *pDoc );
    }

    return GetResource( nResId, &sArg );
}

OUString SAL_CALL SwAccessibleFootnote::getImplementationName()
        throw( RuntimeException )
{
    if( AccessibleRole::END_NOTE == GetRole() )
        return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationNameEndnote));
    else
        return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationNameFootnote));
}

sal_Bool SAL_CALL SwAccessibleFootnote::supportsService(
        const ::rtl::OUString& sTestServiceName)
    throw (::com::sun::star::uno::RuntimeException)
{
    if( sTestServiceName.equalsAsciiL( sAccessibleServiceName,
                                       sizeof(sAccessibleServiceName)-1 ) )
        return sal_True;
    else if( AccessibleRole::END_NOTE == GetRole() )
        return sTestServiceName.equalsAsciiL( sServiceNameEndnote, sizeof(sServiceNameEndnote)-1 );
    else
        return sTestServiceName.equalsAsciiL( sServiceNameFootnote, sizeof(sServiceNameFootnote)-1 );

}

Sequence< OUString > SAL_CALL SwAccessibleFootnote::getSupportedServiceNames()
        throw( ::com::sun::star::uno::RuntimeException )
{
    Sequence< OUString > aRet(2);
    OUString* pArray = aRet.getArray();
    if( AccessibleRole::END_NOTE == GetRole() )
        pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceNameEndnote) );
    else
        pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceNameFootnote) );
    pArray[1] = OUString( RTL_CONSTASCII_USTRINGPARAM(sAccessibleServiceName) );
    return aRet;
}

Sequence< sal_Int8 > SAL_CALL SwAccessibleFootnote::getImplementationId()
        throw(RuntimeException)
{
    vos::OGuard aGuard(Application::GetSolarMutex());
    static Sequence< sal_Int8 > aId( 16 );
    static sal_Bool bInit = sal_False;
    if(!bInit)
    {
        rtl_createUuid( (sal_uInt8 *)(aId.getArray() ), 0, sal_True );
        bInit = sal_True;
    }
    return aId;
}

sal_Bool SwAccessibleFootnote::IsEndnote( const SwFtnFrm *pFtnFrm )
{
    const SwTxtFtn *pTxtFtn = pFtnFrm ->GetAttr();
    return pTxtFtn && pTxtFtn->GetFtn().IsEndNote() ;
}
<|endoftext|>


<commit_before><commit_msg>Remove code commented-out since 2009<commit_after><|endoftext|>


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

#ifndef _SVTOOLS_WIZARDMACHINE_HXX_
#include <svtools/wizardmachine.hxx>
#endif
#ifndef _BASEDLGS_HXX
#include <sfx2/basedlgs.hxx>
#endif
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef _SV_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#ifndef _SV_COMBOBOX_HXX
#include <vcl/combobox.hxx>
#endif
#ifndef _STDCTRL_HXX
#include <svtools/stdctrl.hxx>
#endif
#ifndef _MAILMERGEHELPER_HXX
#include <mailmergehelper.hxx>
#endif
#ifndef _SVEDIT_HXX
#include <svtools/svmedit.hxx>
#endif

class SwMailMergeWizard;
/*-- 17.05.2004 14:51:45---------------------------------------------------

  -----------------------------------------------------------------------*/
class SwGreetingsHandler
{
    friend class SwMailBodyDialog;
    friend class SwMailMergeGreetingsPage;
    CheckBox*           m_pGreetingLineCB;

    CheckBox*           m_pPersonalizedCB;

    FixedText*          m_pFemaleFT;
    ListBox*            m_pFemaleLB;
    PushButton*         m_pFemalePB;

    FixedText*          m_pMaleFT;
    ListBox*            m_pMaleLB;
    PushButton*         m_pMalePB;

    FixedInfo*          m_pFemaleFI;
    FixedText*          m_pFemaleColumnFT;
    ListBox*            m_pFemaleColumnLB;
    FixedText*          m_pFemaleFieldFT;
    ComboBox*           m_pFemaleFieldCB;

    FixedText*          m_pNeutralFT;
    ComboBox*           m_pNeutralCB;

    bool                m_bIsTabPage;

    SwMailMergeWizard*  m_pWizard;

    DECL_LINK(IndividualHdl_Impl, CheckBox*);
    DECL_LINK(GreetingHdl_Impl, PushButton*);

    void    Contains(sal_Bool bContainsGreeting);
    virtual void    UpdatePreview();
};
/*-- 02.04.2004 09:21:06---------------------------------------------------

  -----------------------------------------------------------------------*/
class SwMailMergeGreetingsPage : public svt::OWizardPage,
                                    public SwGreetingsHandler
{
    SwBoldFixedInfo     m_aHeaderFI;

    CheckBox            m_aGreetingLineCB;

    CheckBox            m_aPersonalizedCB;

    FixedText           m_aFemaleFT;
    ListBox             m_aFemaleLB;
    PushButton          m_aFemalePB;

    FixedText           m_aMaleFT;
    ListBox             m_aMaleLB;
    PushButton          m_aMalePB;

    FixedInfo           m_aFemaleFI;
    FixedText           m_aFemaleColumnFT;
    ListBox             m_aFemaleColumnLB;
    FixedText           m_aFemaleFieldFT;
    ComboBox            m_aFemaleFieldCB;

    FixedText           m_aNeutralFT;
    ComboBox            m_aNeutralCB;

    FixedInfo           m_aPreviewFI;
    SwAddressPreview    m_aPreviewWIN;
    PushButton          m_aAssignPB;
    FixedInfo           m_aDocumentIndexFI;
    ImageButton         m_aPrevSetIB;
    ImageButton         m_aNextSetIB;

    String              m_sDocument;

    DECL_LINK(ContainsHdl_Impl, CheckBox*);
    DECL_LINK(InsertDataHdl_Impl, ImageButton*);
    DECL_LINK(GreetingSelectHdl_Impl, ListBox*);
    DECL_LINK(AssignHdl_Impl, PushButton*);

    virtual void    UpdatePreview();
    virtual void        ActivatePage();
    virtual sal_Bool    commitPage( CommitPageReason _eReason );
public:
        SwMailMergeGreetingsPage( SwMailMergeWizard* _pParent);
        ~SwMailMergeGreetingsPage();

};
/*-- 17.05.2004 14:45:43---------------------------------------------------

  -----------------------------------------------------------------------*/
class SwMailBodyDialog : public SfxModalDialog, public SwGreetingsHandler
{
    CheckBox            m_aGreetingLineCB;

    CheckBox            m_aPersonalizedCB;

    FixedText           m_aFemaleFT;
    ListBox             m_aFemaleLB;
    PushButton          m_aFemalePB;

    FixedText           m_aMaleFT;
    ListBox             m_aMaleLB;
    PushButton          m_aMalePB;

    FixedInfo           m_aFemaleFI;
    FixedText           m_aFemaleColumnFT;
    ListBox             m_aFemaleColumnLB;
    FixedText           m_aFemaleFieldFT;
    ComboBox            m_aFemaleFieldCB;

    FixedText           m_aNeutralFT;
    ComboBox            m_aNeutralCB;

    FixedText           m_aBodyFT;
    MultiLineEdit       m_aBodyMLE;
    FixedLine           m_aSeparatorFL;

    OKButton            m_aOK;
    CancelButton        m_aCancel;
    HelpButton          m_aHelp;

    DECL_LINK(ContainsHdl_Impl, CheckBox*);
    DECL_LINK(OKHdl, PushButton*);
public:
    SwMailBodyDialog(Window* pParent, SwMailMergeWizard* pWizard);
    ~SwMailBodyDialog();

    void            SetBody(const String& rBody ) {m_aBodyMLE.SetText(rBody);}
    String          GetBody() const {return m_aBodyMLE.GetText();}
};
#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.5.38); FILE MERGED 2008/04/01 15:58:39 thb 1.5.38.3: #i85898# Stripping all external header guards 2008/04/01 12:55:08 thb 1.5.38.2: #i85898# Stripping all external header guards 2008/03/31 16:57:04 rt 1.5.38.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: mmgreetingspage.hxx,v $
 * $Revision: 1.6 $
 *
 * 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.
 *
 ************************************************************************/
#ifndef _MAILMERGEGREETINGSPAGE_HXX
#define _MAILMERGEGREETINGSPAGE_HXX

#include <svtools/wizardmachine.hxx>
#include <sfx2/basedlgs.hxx>
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#include <vcl/lstbox.hxx>
#include <vcl/combobox.hxx>
#include <svtools/stdctrl.hxx>
#include <mailmergehelper.hxx>
#include <svtools/svmedit.hxx>

class SwMailMergeWizard;
/*-- 17.05.2004 14:51:45---------------------------------------------------

  -----------------------------------------------------------------------*/
class SwGreetingsHandler
{
    friend class SwMailBodyDialog;
    friend class SwMailMergeGreetingsPage;
    CheckBox*           m_pGreetingLineCB;

    CheckBox*           m_pPersonalizedCB;

    FixedText*          m_pFemaleFT;
    ListBox*            m_pFemaleLB;
    PushButton*         m_pFemalePB;

    FixedText*          m_pMaleFT;
    ListBox*            m_pMaleLB;
    PushButton*         m_pMalePB;

    FixedInfo*          m_pFemaleFI;
    FixedText*          m_pFemaleColumnFT;
    ListBox*            m_pFemaleColumnLB;
    FixedText*          m_pFemaleFieldFT;
    ComboBox*           m_pFemaleFieldCB;

    FixedText*          m_pNeutralFT;
    ComboBox*           m_pNeutralCB;

    bool                m_bIsTabPage;

    SwMailMergeWizard*  m_pWizard;

    DECL_LINK(IndividualHdl_Impl, CheckBox*);
    DECL_LINK(GreetingHdl_Impl, PushButton*);

    void    Contains(sal_Bool bContainsGreeting);
    virtual void    UpdatePreview();
};
/*-- 02.04.2004 09:21:06---------------------------------------------------

  -----------------------------------------------------------------------*/
class SwMailMergeGreetingsPage : public svt::OWizardPage,
                                    public SwGreetingsHandler
{
    SwBoldFixedInfo     m_aHeaderFI;

    CheckBox            m_aGreetingLineCB;

    CheckBox            m_aPersonalizedCB;

    FixedText           m_aFemaleFT;
    ListBox             m_aFemaleLB;
    PushButton          m_aFemalePB;

    FixedText           m_aMaleFT;
    ListBox             m_aMaleLB;
    PushButton          m_aMalePB;

    FixedInfo           m_aFemaleFI;
    FixedText           m_aFemaleColumnFT;
    ListBox             m_aFemaleColumnLB;
    FixedText           m_aFemaleFieldFT;
    ComboBox            m_aFemaleFieldCB;

    FixedText           m_aNeutralFT;
    ComboBox            m_aNeutralCB;

    FixedInfo           m_aPreviewFI;
    SwAddressPreview    m_aPreviewWIN;
    PushButton          m_aAssignPB;
    FixedInfo           m_aDocumentIndexFI;
    ImageButton         m_aPrevSetIB;
    ImageButton         m_aNextSetIB;

    String              m_sDocument;

    DECL_LINK(ContainsHdl_Impl, CheckBox*);
    DECL_LINK(InsertDataHdl_Impl, ImageButton*);
    DECL_LINK(GreetingSelectHdl_Impl, ListBox*);
    DECL_LINK(AssignHdl_Impl, PushButton*);

    virtual void    UpdatePreview();
    virtual void        ActivatePage();
    virtual sal_Bool    commitPage( CommitPageReason _eReason );
public:
        SwMailMergeGreetingsPage( SwMailMergeWizard* _pParent);
        ~SwMailMergeGreetingsPage();

};
/*-- 17.05.2004 14:45:43---------------------------------------------------

  -----------------------------------------------------------------------*/
class SwMailBodyDialog : public SfxModalDialog, public SwGreetingsHandler
{
    CheckBox            m_aGreetingLineCB;

    CheckBox            m_aPersonalizedCB;

    FixedText           m_aFemaleFT;
    ListBox             m_aFemaleLB;
    PushButton          m_aFemalePB;

    FixedText           m_aMaleFT;
    ListBox             m_aMaleLB;
    PushButton          m_aMalePB;

    FixedInfo           m_aFemaleFI;
    FixedText           m_aFemaleColumnFT;
    ListBox             m_aFemaleColumnLB;
    FixedText           m_aFemaleFieldFT;
    ComboBox            m_aFemaleFieldCB;

    FixedText           m_aNeutralFT;
    ComboBox            m_aNeutralCB;

    FixedText           m_aBodyFT;
    MultiLineEdit       m_aBodyMLE;
    FixedLine           m_aSeparatorFL;

    OKButton            m_aOK;
    CancelButton        m_aCancel;
    HelpButton          m_aHelp;

    DECL_LINK(ContainsHdl_Impl, CheckBox*);
    DECL_LINK(OKHdl, PushButton*);
public:
    SwMailBodyDialog(Window* pParent, SwMailMergeWizard* pWizard);
    ~SwMailBodyDialog();

    void            SetBody(const String& rBody ) {m_aBodyMLE.SetText(rBody);}
    String          GetBody() const {return m_aBodyMLE.GetText();}
};
#endif

<|endoftext|>


<commit_before>// Copyright (c) 2020-2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <crypto/hmac_sha256.h>
#include <crypto/hmac_sha512.h>
#include <crypto/ripemd160.h>
#include <crypto/sha1.h>
#include <crypto/sha256.h>
#include <crypto/sha3.h>
#include <crypto/sha512.h>
#include <hash.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>

#include <cstdint>
#include <vector>

FUZZ_TARGET(crypto)
{
    FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
    std::vector<uint8_t> data = ConsumeRandomLengthByteVector(fuzzed_data_provider);
    if (data.empty()) {
        data.resize(fuzzed_data_provider.ConsumeIntegralInRange<size_t>(1, 4096), fuzzed_data_provider.ConsumeIntegral<uint8_t>());
    }

    CHash160 hash160;
    CHash256 hash256;
    CHMAC_SHA256 hmac_sha256{data.data(), data.size()};
    CHMAC_SHA512 hmac_sha512{data.data(), data.size()};
    CRIPEMD160 ripemd160;
    CSHA1 sha1;
    CSHA256 sha256;
    CSHA512 sha512;
    SHA3_256 sha3;
    CSipHasher sip_hasher{fuzzed_data_provider.ConsumeIntegral<uint64_t>(), fuzzed_data_provider.ConsumeIntegral<uint64_t>()};

    while (fuzzed_data_provider.ConsumeBool()) {
        CallOneOf(
            fuzzed_data_provider,
            [&] {
                if (fuzzed_data_provider.ConsumeBool()) {
                    data = ConsumeRandomLengthByteVector(fuzzed_data_provider);
                    if (data.empty()) {
                        data.resize(fuzzed_data_provider.ConsumeIntegralInRange<size_t>(1, 4096), fuzzed_data_provider.ConsumeIntegral<uint8_t>());
                    }
                }

                (void)hash160.Write(data);
                (void)hash256.Write(data);
                (void)hmac_sha256.Write(data.data(), data.size());
                (void)hmac_sha512.Write(data.data(), data.size());
                (void)ripemd160.Write(data.data(), data.size());
                (void)sha1.Write(data.data(), data.size());
                (void)sha256.Write(data.data(), data.size());
                (void)sha3.Write(data);
                (void)sha512.Write(data.data(), data.size());
                (void)sip_hasher.Write(data.data(), data.size());

                (void)Hash(data);
                (void)Hash160(data);
                (void)sha512.Size();
            },
            [&] {
                (void)hash160.Reset();
                (void)hash256.Reset();
                (void)ripemd160.Reset();
                (void)sha1.Reset();
                (void)sha256.Reset();
                (void)sha3.Reset();
                (void)sha512.Reset();
            },
            [&] {
                CallOneOf(
                    fuzzed_data_provider,
                    [&] {
                        data.resize(CHash160::OUTPUT_SIZE);
                        hash160.Finalize(data);
                    },
                    [&] {
                        data.resize(CHash256::OUTPUT_SIZE);
                        hash256.Finalize(data);
                    },
                    [&] {
                        data.resize(CHMAC_SHA256::OUTPUT_SIZE);
                        hmac_sha256.Finalize(data.data());
                    },
                    [&] {
                        data.resize(CHMAC_SHA512::OUTPUT_SIZE);
                        hmac_sha512.Finalize(data.data());
                    },
                    [&] {
                        data.resize(CRIPEMD160::OUTPUT_SIZE);
                        ripemd160.Finalize(data.data());
                    },
                    [&] {
                        data.resize(CSHA1::OUTPUT_SIZE);
                        sha1.Finalize(data.data());
                    },
                    [&] {
                        data.resize(CSHA256::OUTPUT_SIZE);
                        sha256.Finalize(data.data());
                    },
                    [&] {
                        data.resize(CSHA512::OUTPUT_SIZE);
                        sha512.Finalize(data.data());
                    },
                    [&] {
                        data.resize(1);
                        data[0] = sip_hasher.Finalize() % 256;
                    },
                    [&] {
                        data.resize(SHA3_256::OUTPUT_SIZE);
                        sha3.Finalize(data);
                    });
            });
    }
    if (fuzzed_data_provider.ConsumeBool()) {
        uint64_t state[25];
        for (size_t i = 0; i < 25; ++i) {
            state[i] = fuzzed_data_provider.ConsumeIntegral<uint64_t>();
        }
        KeccakF(state);
    }
}
<commit_msg>fuzz: Speed up crypto fuzz target<commit_after>// Copyright (c) 2020-2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <crypto/hmac_sha256.h>
#include <crypto/hmac_sha512.h>
#include <crypto/ripemd160.h>
#include <crypto/sha1.h>
#include <crypto/sha256.h>
#include <crypto/sha3.h>
#include <crypto/sha512.h>
#include <hash.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>

#include <cstdint>
#include <vector>

FUZZ_TARGET(crypto)
{
    // Hashing is expensive with sanitizers enabled, so limit the number of
    // calls
    int limit_max_ops{30};

    FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
    std::vector<uint8_t> data = ConsumeRandomLengthByteVector(fuzzed_data_provider);
    if (data.empty()) {
        data.resize(fuzzed_data_provider.ConsumeIntegralInRange<size_t>(1, 4096), fuzzed_data_provider.ConsumeIntegral<uint8_t>());
    }

    CHash160 hash160;
    CHash256 hash256;
    CHMAC_SHA256 hmac_sha256{data.data(), data.size()};
    CHMAC_SHA512 hmac_sha512{data.data(), data.size()};
    CRIPEMD160 ripemd160;
    CSHA1 sha1;
    CSHA256 sha256;
    CSHA512 sha512;
    SHA3_256 sha3;
    CSipHasher sip_hasher{fuzzed_data_provider.ConsumeIntegral<uint64_t>(), fuzzed_data_provider.ConsumeIntegral<uint64_t>()};

    while (--limit_max_ops >= 0 && fuzzed_data_provider.ConsumeBool()) {
        CallOneOf(
            fuzzed_data_provider,
            [&] {
                if (fuzzed_data_provider.ConsumeBool()) {
                    data = ConsumeRandomLengthByteVector(fuzzed_data_provider);
                    if (data.empty()) {
                        data.resize(fuzzed_data_provider.ConsumeIntegralInRange<size_t>(1, 4096), fuzzed_data_provider.ConsumeIntegral<uint8_t>());
                    }
                }

                (void)hash160.Write(data);
                (void)hash256.Write(data);
                (void)hmac_sha256.Write(data.data(), data.size());
                (void)hmac_sha512.Write(data.data(), data.size());
                (void)ripemd160.Write(data.data(), data.size());
                (void)sha1.Write(data.data(), data.size());
                (void)sha256.Write(data.data(), data.size());
                (void)sha3.Write(data);
                (void)sha512.Write(data.data(), data.size());
                (void)sip_hasher.Write(data.data(), data.size());

                (void)Hash(data);
                (void)Hash160(data);
                (void)sha512.Size();
            },
            [&] {
                (void)hash160.Reset();
                (void)hash256.Reset();
                (void)ripemd160.Reset();
                (void)sha1.Reset();
                (void)sha256.Reset();
                (void)sha3.Reset();
                (void)sha512.Reset();
            },
            [&] {
                CallOneOf(
                    fuzzed_data_provider,
                    [&] {
                        data.resize(CHash160::OUTPUT_SIZE);
                        hash160.Finalize(data);
                    },
                    [&] {
                        data.resize(CHash256::OUTPUT_SIZE);
                        hash256.Finalize(data);
                    },
                    [&] {
                        data.resize(CHMAC_SHA256::OUTPUT_SIZE);
                        hmac_sha256.Finalize(data.data());
                    },
                    [&] {
                        data.resize(CHMAC_SHA512::OUTPUT_SIZE);
                        hmac_sha512.Finalize(data.data());
                    },
                    [&] {
                        data.resize(CRIPEMD160::OUTPUT_SIZE);
                        ripemd160.Finalize(data.data());
                    },
                    [&] {
                        data.resize(CSHA1::OUTPUT_SIZE);
                        sha1.Finalize(data.data());
                    },
                    [&] {
                        data.resize(CSHA256::OUTPUT_SIZE);
                        sha256.Finalize(data.data());
                    },
                    [&] {
                        data.resize(CSHA512::OUTPUT_SIZE);
                        sha512.Finalize(data.data());
                    },
                    [&] {
                        data.resize(1);
                        data[0] = sip_hasher.Finalize() % 256;
                    },
                    [&] {
                        data.resize(SHA3_256::OUTPUT_SIZE);
                        sha3.Finalize(data);
                    });
            });
    }
    if (fuzzed_data_provider.ConsumeBool()) {
        uint64_t state[25];
        for (size_t i = 0; i < 25; ++i) {
            state[i] = fuzzed_data_provider.ConsumeIntegral<uint64_t>();
        }
        KeccakF(state);
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2019-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <chainparams.h>
#include <compressor.h>
#include <core_io.h>
#include <core_memusage.h>
#include <policy/policy.h>
#include <pubkey.h>
#include <script/descriptor.h>
#include <script/interpreter.h>
#include <script/script.h>
#include <script/script_error.h>
#include <script/sign.h>
#include <script/signingprovider.h>
#include <script/standard.h>
#include <streams.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>
#include <univalue.h>
#include <util/memory.h>

#include <algorithm>
#include <cassert>
#include <cstdint>
#include <optional>
#include <string>
#include <vector>

void initialize_script()
{
    // Fuzzers using pubkey must hold an ECCVerifyHandle.
    static const ECCVerifyHandle verify_handle;

    SelectParams(CBaseChainParams::REGTEST);
}

FUZZ_TARGET_INIT(script, initialize_script)
{
    FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
    const std::optional<CScript> script_opt = ConsumeDeserializable<CScript>(fuzzed_data_provider);
    if (!script_opt) return;
    const CScript script{*script_opt};

    std::vector<unsigned char> compressed;
    if (CompressScript(script, compressed)) {
        const unsigned int size = compressed[0];
        compressed.erase(compressed.begin());
        assert(size <= 5);
        CScript decompressed_script;
        const bool ok = DecompressScript(decompressed_script, size, compressed);
        assert(ok);
        assert(script == decompressed_script);
    }

    CTxDestination address;
    (void)ExtractDestination(script, address);

    TxoutType type_ret;
    std::vector<CTxDestination> addresses;
    int required_ret;
    (void)ExtractDestinations(script, type_ret, addresses, required_ret);

    const FlatSigningProvider signing_provider;
    (void)InferDescriptor(script, signing_provider);

    (void)IsSegWitOutput(signing_provider, script);

    (void)IsSolvable(signing_provider, script);

    TxoutType which_type;
    (void)IsStandard(script, which_type);

    (void)RecursiveDynamicUsage(script);

    std::vector<std::vector<unsigned char>> solutions;
    (void)Solver(script, solutions);

    (void)script.HasValidOps();
    (void)script.IsPayToScriptHash();
    (void)script.IsPayToWitnessScriptHash();
    (void)script.IsPushOnly();
    (void)script.IsUnspendable();
    (void)script.GetSigOpCount(/* fAccurate= */ false);

    (void)FormatScript(script);
    (void)ScriptToAsmStr(script, false);
    (void)ScriptToAsmStr(script, true);

    UniValue o1(UniValue::VOBJ);
    ScriptPubKeyToUniv(script, o1, true);
    UniValue o2(UniValue::VOBJ);
    ScriptPubKeyToUniv(script, o2, false);
    UniValue o3(UniValue::VOBJ);
    ScriptToUniv(script, o3, true);
    UniValue o4(UniValue::VOBJ);
    ScriptToUniv(script, o4, false);

    {
        const std::vector<uint8_t> bytes = ConsumeRandomLengthByteVector(fuzzed_data_provider);
        // DecompressScript(..., ..., bytes) is not guaranteed to be defined if the bytes vector is too short
        if (bytes.size() >= 32) {
            CScript decompressed_script;
            DecompressScript(decompressed_script, fuzzed_data_provider.ConsumeIntegral<unsigned int>(), bytes);
        }
    }

    const std::optional<CScript> other_script = ConsumeDeserializable<CScript>(fuzzed_data_provider);
    if (other_script) {
        {
            CScript script_mut{script};
            (void)FindAndDelete(script_mut, *other_script);
        }
        const std::vector<std::string> random_string_vector = ConsumeRandomLengthStringVector(fuzzed_data_provider);
        const uint32_t u32{fuzzed_data_provider.ConsumeIntegral<uint32_t>()};
        const uint32_t flags{u32 | SCRIPT_VERIFY_P2SH};
        {
            CScriptWitness wit;
            for (const auto& s : random_string_vector) {
                wit.stack.emplace_back(s.begin(), s.end());
            }
            (void)CountWitnessSigOps(script, *other_script, &wit, flags);
            wit.SetNull();
        }
    }

    (void)GetOpName(ConsumeOpcodeType(fuzzed_data_provider));
    (void)ScriptErrorString(static_cast<ScriptError>(fuzzed_data_provider.ConsumeIntegralInRange<int>(0, SCRIPT_ERR_ERROR_COUNT)));

    {
        const std::vector<uint8_t> bytes = ConsumeRandomLengthByteVector(fuzzed_data_provider);
        CScript append_script{bytes.begin(), bytes.end()};
        append_script << fuzzed_data_provider.ConsumeIntegral<int64_t>();
        append_script << ConsumeOpcodeType(fuzzed_data_provider);
        append_script << CScriptNum{fuzzed_data_provider.ConsumeIntegral<int64_t>()};
        append_script << ConsumeRandomLengthByteVector(fuzzed_data_provider);
    }

    {
        WitnessUnknown witness_unknown_1{};
        witness_unknown_1.version = fuzzed_data_provider.ConsumeIntegral<int>();
        const std::vector<uint8_t> witness_unknown_program_1 = fuzzed_data_provider.ConsumeBytes<uint8_t>(40);
        witness_unknown_1.length = witness_unknown_program_1.size();
        std::copy(witness_unknown_program_1.begin(), witness_unknown_program_1.end(), witness_unknown_1.program);

        WitnessUnknown witness_unknown_2{};
        witness_unknown_2.version = fuzzed_data_provider.ConsumeIntegral<int>();
        const std::vector<uint8_t> witness_unknown_program_2 = fuzzed_data_provider.ConsumeBytes<uint8_t>(40);
        witness_unknown_2.length = witness_unknown_program_2.size();
        std::copy(witness_unknown_program_2.begin(), witness_unknown_program_2.end(), witness_unknown_2.program);

        (void)(witness_unknown_1 == witness_unknown_2);
        (void)(witness_unknown_1 < witness_unknown_2);
    }

    {
        const CTxDestination tx_destination_1 = ConsumeTxDestination(fuzzed_data_provider);
        const CTxDestination tx_destination_2 = ConsumeTxDestination(fuzzed_data_provider);
        (void)(tx_destination_1 == tx_destination_2);
        (void)(tx_destination_1 < tx_destination_2);
    }
}
<commit_msg>fuzz: Check that NULL_DATA is unspendable<commit_after>// Copyright (c) 2019-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <chainparams.h>
#include <compressor.h>
#include <core_io.h>
#include <core_memusage.h>
#include <policy/policy.h>
#include <pubkey.h>
#include <script/descriptor.h>
#include <script/interpreter.h>
#include <script/script.h>
#include <script/script_error.h>
#include <script/sign.h>
#include <script/signingprovider.h>
#include <script/standard.h>
#include <streams.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>
#include <univalue.h>
#include <util/memory.h>

#include <algorithm>
#include <cassert>
#include <cstdint>
#include <optional>
#include <string>
#include <vector>

void initialize_script()
{
    // Fuzzers using pubkey must hold an ECCVerifyHandle.
    static const ECCVerifyHandle verify_handle;

    SelectParams(CBaseChainParams::REGTEST);
}

FUZZ_TARGET_INIT(script, initialize_script)
{
    FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
    const std::optional<CScript> script_opt = ConsumeDeserializable<CScript>(fuzzed_data_provider);
    if (!script_opt) return;
    const CScript script{*script_opt};

    std::vector<unsigned char> compressed;
    if (CompressScript(script, compressed)) {
        const unsigned int size = compressed[0];
        compressed.erase(compressed.begin());
        assert(size <= 5);
        CScript decompressed_script;
        const bool ok = DecompressScript(decompressed_script, size, compressed);
        assert(ok);
        assert(script == decompressed_script);
    }

    CTxDestination address;
    (void)ExtractDestination(script, address);

    TxoutType type_ret;
    std::vector<CTxDestination> addresses;
    int required_ret;
    (void)ExtractDestinations(script, type_ret, addresses, required_ret);

    const FlatSigningProvider signing_provider;
    (void)InferDescriptor(script, signing_provider);

    (void)IsSegWitOutput(signing_provider, script);

    (void)IsSolvable(signing_provider, script);

    TxoutType which_type;
    (void)IsStandard(script, which_type);
    if (which_type == TxoutType::NULL_DATA) {
        assert(script.IsUnspendable());
    }
    if (script.IsUnspendable()) {
        assert(which_type == TxoutType::NULL_DATA ||
               which_type == TxoutType::NONSTANDARD);
    }

    (void)RecursiveDynamicUsage(script);

    std::vector<std::vector<unsigned char>> solutions;
    (void)Solver(script, solutions);

    (void)script.HasValidOps();
    (void)script.IsPayToScriptHash();
    (void)script.IsPayToWitnessScriptHash();
    (void)script.IsPushOnly();
    (void)script.GetSigOpCount(/* fAccurate= */ false);

    (void)FormatScript(script);
    (void)ScriptToAsmStr(script, false);
    (void)ScriptToAsmStr(script, true);

    UniValue o1(UniValue::VOBJ);
    ScriptPubKeyToUniv(script, o1, true);
    UniValue o2(UniValue::VOBJ);
    ScriptPubKeyToUniv(script, o2, false);
    UniValue o3(UniValue::VOBJ);
    ScriptToUniv(script, o3, true);
    UniValue o4(UniValue::VOBJ);
    ScriptToUniv(script, o4, false);

    {
        const std::vector<uint8_t> bytes = ConsumeRandomLengthByteVector(fuzzed_data_provider);
        // DecompressScript(..., ..., bytes) is not guaranteed to be defined if the bytes vector is too short
        if (bytes.size() >= 32) {
            CScript decompressed_script;
            DecompressScript(decompressed_script, fuzzed_data_provider.ConsumeIntegral<unsigned int>(), bytes);
        }
    }

    const std::optional<CScript> other_script = ConsumeDeserializable<CScript>(fuzzed_data_provider);
    if (other_script) {
        {
            CScript script_mut{script};
            (void)FindAndDelete(script_mut, *other_script);
        }
        const std::vector<std::string> random_string_vector = ConsumeRandomLengthStringVector(fuzzed_data_provider);
        const uint32_t u32{fuzzed_data_provider.ConsumeIntegral<uint32_t>()};
        const uint32_t flags{u32 | SCRIPT_VERIFY_P2SH};
        {
            CScriptWitness wit;
            for (const auto& s : random_string_vector) {
                wit.stack.emplace_back(s.begin(), s.end());
            }
            (void)CountWitnessSigOps(script, *other_script, &wit, flags);
            wit.SetNull();
        }
    }

    (void)GetOpName(ConsumeOpcodeType(fuzzed_data_provider));
    (void)ScriptErrorString(static_cast<ScriptError>(fuzzed_data_provider.ConsumeIntegralInRange<int>(0, SCRIPT_ERR_ERROR_COUNT)));

    {
        const std::vector<uint8_t> bytes = ConsumeRandomLengthByteVector(fuzzed_data_provider);
        CScript append_script{bytes.begin(), bytes.end()};
        append_script << fuzzed_data_provider.ConsumeIntegral<int64_t>();
        append_script << ConsumeOpcodeType(fuzzed_data_provider);
        append_script << CScriptNum{fuzzed_data_provider.ConsumeIntegral<int64_t>()};
        append_script << ConsumeRandomLengthByteVector(fuzzed_data_provider);
    }

    {
        WitnessUnknown witness_unknown_1{};
        witness_unknown_1.version = fuzzed_data_provider.ConsumeIntegral<int>();
        const std::vector<uint8_t> witness_unknown_program_1 = fuzzed_data_provider.ConsumeBytes<uint8_t>(40);
        witness_unknown_1.length = witness_unknown_program_1.size();
        std::copy(witness_unknown_program_1.begin(), witness_unknown_program_1.end(), witness_unknown_1.program);

        WitnessUnknown witness_unknown_2{};
        witness_unknown_2.version = fuzzed_data_provider.ConsumeIntegral<int>();
        const std::vector<uint8_t> witness_unknown_program_2 = fuzzed_data_provider.ConsumeBytes<uint8_t>(40);
        witness_unknown_2.length = witness_unknown_program_2.size();
        std::copy(witness_unknown_program_2.begin(), witness_unknown_program_2.end(), witness_unknown_2.program);

        (void)(witness_unknown_1 == witness_unknown_2);
        (void)(witness_unknown_1 < witness_unknown_2);
    }

    {
        const CTxDestination tx_destination_1 = ConsumeTxDestination(fuzzed_data_provider);
        const CTxDestination tx_destination_2 = ConsumeTxDestination(fuzzed_data_provider);
        (void)(tx_destination_1 == tx_destination_2);
        (void)(tx_destination_1 < tx_destination_2);
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2020-2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <blockfilter.h>
#include <clientversion.h>
#include <logging.h>
#include <netaddress.h>
#include <netbase.h>
#include <outputtype.h>
#include <rpc/client.h>
#include <rpc/request.h>
#include <rpc/server.h>
#include <rpc/util.h>
#include <script/descriptor.h>
#include <script/script.h>
#include <serialize.h>
#include <streams.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>
#include <util/error.h>
#include <util/fees.h>
#include <util/message.h>
#include <util/settings.h>
#include <util/strencodings.h>
#include <util/string.h>
#include <util/system.h>
#include <util/translation.h>
#include <util/url.h>
#include <version.h>

#include <cstdint>
#include <cstdlib>
#include <string>
#include <vector>

namespace {
bool LegacyParsePrechecks(const std::string& str)
{
    if (str.empty()) // No empty string allowed
        return false;
    if (str.size() >= 1 && (IsSpace(str[0]) || IsSpace(str[str.size() - 1]))) // No padding allowed
        return false;
    if (!ValidAsCString(str)) // No embedded NUL characters allowed
        return false;
    return true;
}

bool LegacyParseInt32(const std::string& str, int32_t* out)
{
    if (!LegacyParsePrechecks(str))
        return false;
    char* endp = nullptr;
    errno = 0; // strtol will not set errno if valid
    long int n = strtol(str.c_str(), &endp, 10);
    if (out) *out = (int32_t)n;
    // Note that strtol returns a *long int*, so even if strtol doesn't report an over/underflow
    // we still have to check that the returned value is within the range of an *int32_t*. On 64-bit
    // platforms the size of these types may be different.
    return endp && *endp == 0 && !errno &&
           n >= std::numeric_limits<int32_t>::min() &&
           n <= std::numeric_limits<int32_t>::max();
}

bool LegacyParseInt64(const std::string& str, int64_t* out)
{
    if (!LegacyParsePrechecks(str))
        return false;
    char* endp = nullptr;
    errno = 0; // strtoll will not set errno if valid
    long long int n = strtoll(str.c_str(), &endp, 10);
    if (out) *out = (int64_t)n;
    // Note that strtoll returns a *long long int*, so even if strtol doesn't report an over/underflow
    // we still have to check that the returned value is within the range of an *int64_t*.
    return endp && *endp == 0 && !errno &&
           n >= std::numeric_limits<int64_t>::min() &&
           n <= std::numeric_limits<int64_t>::max();
}

bool LegacyParseUInt32(const std::string& str, uint32_t* out)
{
    if (!LegacyParsePrechecks(str))
        return false;
    if (str.size() >= 1 && str[0] == '-') // Reject negative values, unfortunately strtoul accepts these by default if they fit in the range
        return false;
    char* endp = nullptr;
    errno = 0; // strtoul will not set errno if valid
    unsigned long int n = strtoul(str.c_str(), &endp, 10);
    if (out) *out = (uint32_t)n;
    // Note that strtoul returns a *unsigned long int*, so even if it doesn't report an over/underflow
    // we still have to check that the returned value is within the range of an *uint32_t*. On 64-bit
    // platforms the size of these types may be different.
    return endp && *endp == 0 && !errno &&
           n <= std::numeric_limits<uint32_t>::max();
}

bool LegacyParseUInt8(const std::string& str, uint8_t* out)
{
    uint32_t u32;
    if (!LegacyParseUInt32(str, &u32) || u32 > std::numeric_limits<uint8_t>::max()) {
        return false;
    }
    if (out != nullptr) {
        *out = static_cast<uint8_t>(u32);
    }
    return true;
}

bool LegacyParseUInt64(const std::string& str, uint64_t* out)
{
    if (!LegacyParsePrechecks(str))
        return false;
    if (str.size() >= 1 && str[0] == '-') // Reject negative values, unfortunately strtoull accepts these by default if they fit in the range
        return false;
    char* endp = nullptr;
    errno = 0; // strtoull will not set errno if valid
    unsigned long long int n = strtoull(str.c_str(), &endp, 10);
    if (out) *out = (uint64_t)n;
    // Note that strtoull returns a *unsigned long long int*, so even if it doesn't report an over/underflow
    // we still have to check that the returned value is within the range of an *uint64_t*.
    return endp && *endp == 0 && !errno &&
           n <= std::numeric_limits<uint64_t>::max();
}

// For backwards compatibility checking.
int64_t atoi64_legacy(const std::string& str)
{
    return strtoll(str.c_str(), nullptr, 10);
}
}; // namespace

FUZZ_TARGET(string)
{
    FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
    const std::string random_string_1 = fuzzed_data_provider.ConsumeRandomLengthString(32);
    const std::string random_string_2 = fuzzed_data_provider.ConsumeRandomLengthString(32);
    const std::vector<std::string> random_string_vector = ConsumeRandomLengthStringVector(fuzzed_data_provider);

    (void)AmountErrMsg(random_string_1, random_string_2);
    (void)AmountHighWarn(random_string_1);
    BlockFilterType block_filter_type;
    (void)BlockFilterTypeByName(random_string_1, block_filter_type);
    (void)Capitalize(random_string_1);
    (void)CopyrightHolders(random_string_1);
    FeeEstimateMode fee_estimate_mode;
    (void)FeeModeFromString(random_string_1, fee_estimate_mode);
    const auto width{fuzzed_data_provider.ConsumeIntegralInRange<size_t>(1, 1000)};
    (void)FormatParagraph(random_string_1, width, fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, width));
    (void)FormatSubVersion(random_string_1, fuzzed_data_provider.ConsumeIntegral<int>(), random_string_vector);
    (void)GetDescriptorChecksum(random_string_1);
    (void)HelpExampleCli(random_string_1, random_string_2);
    (void)HelpExampleRpc(random_string_1, random_string_2);
    (void)HelpMessageGroup(random_string_1);
    (void)HelpMessageOpt(random_string_1, random_string_2);
    (void)IsDeprecatedRPCEnabled(random_string_1);
    (void)Join(random_string_vector, random_string_1);
    (void)JSONRPCError(fuzzed_data_provider.ConsumeIntegral<int>(), random_string_1);
    const util::Settings settings;
    (void)OnlyHasDefaultSectionSetting(settings, random_string_1, random_string_2);
    (void)ParseNetwork(random_string_1);
    try {
        (void)ParseNonRFCJSONValue(random_string_1);
    } catch (const std::runtime_error&) {
    }
    (void)ParseOutputType(random_string_1);
    (void)RemovePrefix(random_string_1, random_string_2);
    (void)ResolveErrMsg(random_string_1, random_string_2);
    try {
        (void)RPCConvertNamedValues(random_string_1, random_string_vector);
    } catch (const std::runtime_error&) {
    }
    try {
        (void)RPCConvertValues(random_string_1, random_string_vector);
    } catch (const std::runtime_error&) {
    }
    (void)SanitizeString(random_string_1);
    (void)SanitizeString(random_string_1, fuzzed_data_provider.ConsumeIntegralInRange<int>(0, 3));
#ifndef WIN32
    (void)ShellEscape(random_string_1);
#endif // WIN32
    uint16_t port_out;
    std::string host_out;
    SplitHostPort(random_string_1, port_out, host_out);
    (void)TimingResistantEqual(random_string_1, random_string_2);
    (void)ToLower(random_string_1);
    (void)ToUpper(random_string_1);
    (void)TrimString(random_string_1);
    (void)TrimString(random_string_1, random_string_2);
    (void)urlDecode(random_string_1);
    (void)ValidAsCString(random_string_1);
    (void)_(random_string_1.c_str());
    try {
        throw scriptnum_error{random_string_1};
    } catch (const std::runtime_error&) {
    }

    {
        CDataStream data_stream{SER_NETWORK, INIT_PROTO_VERSION};
        std::string s;
        auto limited_string = LIMITED_STRING(s, 10);
        data_stream << random_string_1;
        try {
            data_stream >> limited_string;
            assert(data_stream.empty());
            assert(s.size() <= random_string_1.size());
            assert(s.size() <= 10);
            if (!random_string_1.empty()) {
                assert(!s.empty());
            }
        } catch (const std::ios_base::failure&) {
        }
    }
    {
        CDataStream data_stream{SER_NETWORK, INIT_PROTO_VERSION};
        const auto limited_string = LIMITED_STRING(random_string_1, 10);
        data_stream << limited_string;
        std::string deserialized_string;
        data_stream >> deserialized_string;
        assert(data_stream.empty());
        assert(deserialized_string == random_string_1);
    }
    {
        int64_t amount_out;
        (void)ParseFixedPoint(random_string_1, fuzzed_data_provider.ConsumeIntegralInRange<int>(0, 1024), &amount_out);
    }
    {
        (void)Untranslated(random_string_1);
        const bilingual_str bs1{random_string_1, random_string_2};
        const bilingual_str bs2{random_string_2, random_string_1};
        (void)(bs1 + bs2);
    }
    {
        int32_t i32;
        int64_t i64;
        uint32_t u32;
        uint64_t u64;
        uint8_t u8;
        const bool ok_i32 = ParseInt32(random_string_1, &i32);
        const bool ok_i64 = ParseInt64(random_string_1, &i64);
        const bool ok_u32 = ParseUInt32(random_string_1, &u32);
        const bool ok_u64 = ParseUInt64(random_string_1, &u64);
        const bool ok_u8 = ParseUInt8(random_string_1, &u8);

        int32_t i32_legacy;
        int64_t i64_legacy;
        uint32_t u32_legacy;
        uint64_t u64_legacy;
        uint8_t u8_legacy;
        const bool ok_i32_legacy = LegacyParseInt32(random_string_1, &i32_legacy);
        const bool ok_i64_legacy = LegacyParseInt64(random_string_1, &i64_legacy);
        const bool ok_u32_legacy = LegacyParseUInt32(random_string_1, &u32_legacy);
        const bool ok_u64_legacy = LegacyParseUInt64(random_string_1, &u64_legacy);
        const bool ok_u8_legacy = LegacyParseUInt8(random_string_1, &u8_legacy);

        assert(ok_i32 == ok_i32_legacy);
        assert(ok_i64 == ok_i64_legacy);
        assert(ok_u32 == ok_u32_legacy);
        assert(ok_u64 == ok_u64_legacy);
        assert(ok_u8 == ok_u8_legacy);

        if (ok_i32) {
            assert(i32 == i32_legacy);
        }
        if (ok_i64) {
            assert(i64 == i64_legacy);
        }
        if (ok_u32) {
            assert(u32 == u32_legacy);
        }
        if (ok_u64) {
            assert(u64 == u64_legacy);
        }
        if (ok_u8) {
            assert(u8 == u8_legacy);
        }
    }

    {
        const int locale_independent_atoi_result = LocaleIndependentAtoi<int>(random_string_1);
        const int64_t atoi64_result = atoi64_legacy(random_string_1);
        assert(locale_independent_atoi_result == std::clamp<int64_t>(atoi64_result, std::numeric_limits<int>::min(), std::numeric_limits<int>::max()));
    }

    {
        const int64_t atoi64_result = atoi64_legacy(random_string_1);
        const int64_t locale_independent_atoi_result = LocaleIndependentAtoi<int64_t>(random_string_1);
        assert(atoi64_result == locale_independent_atoi_result);
    }
}
<commit_msg>fuzz: add `SplitString` fuzz target<commit_after>// Copyright (c) 2020-2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <blockfilter.h>
#include <clientversion.h>
#include <logging.h>
#include <netaddress.h>
#include <netbase.h>
#include <outputtype.h>
#include <rpc/client.h>
#include <rpc/request.h>
#include <rpc/server.h>
#include <rpc/util.h>
#include <script/descriptor.h>
#include <script/script.h>
#include <serialize.h>
#include <streams.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>
#include <util/error.h>
#include <util/fees.h>
#include <util/message.h>
#include <util/settings.h>
#include <util/strencodings.h>
#include <util/string.h>
#include <util/system.h>
#include <util/translation.h>
#include <util/url.h>
#include <version.h>

#include <cstdint>
#include <cstdlib>
#include <string>
#include <vector>

namespace {
bool LegacyParsePrechecks(const std::string& str)
{
    if (str.empty()) // No empty string allowed
        return false;
    if (str.size() >= 1 && (IsSpace(str[0]) || IsSpace(str[str.size() - 1]))) // No padding allowed
        return false;
    if (!ValidAsCString(str)) // No embedded NUL characters allowed
        return false;
    return true;
}

bool LegacyParseInt32(const std::string& str, int32_t* out)
{
    if (!LegacyParsePrechecks(str))
        return false;
    char* endp = nullptr;
    errno = 0; // strtol will not set errno if valid
    long int n = strtol(str.c_str(), &endp, 10);
    if (out) *out = (int32_t)n;
    // Note that strtol returns a *long int*, so even if strtol doesn't report an over/underflow
    // we still have to check that the returned value is within the range of an *int32_t*. On 64-bit
    // platforms the size of these types may be different.
    return endp && *endp == 0 && !errno &&
           n >= std::numeric_limits<int32_t>::min() &&
           n <= std::numeric_limits<int32_t>::max();
}

bool LegacyParseInt64(const std::string& str, int64_t* out)
{
    if (!LegacyParsePrechecks(str))
        return false;
    char* endp = nullptr;
    errno = 0; // strtoll will not set errno if valid
    long long int n = strtoll(str.c_str(), &endp, 10);
    if (out) *out = (int64_t)n;
    // Note that strtoll returns a *long long int*, so even if strtol doesn't report an over/underflow
    // we still have to check that the returned value is within the range of an *int64_t*.
    return endp && *endp == 0 && !errno &&
           n >= std::numeric_limits<int64_t>::min() &&
           n <= std::numeric_limits<int64_t>::max();
}

bool LegacyParseUInt32(const std::string& str, uint32_t* out)
{
    if (!LegacyParsePrechecks(str))
        return false;
    if (str.size() >= 1 && str[0] == '-') // Reject negative values, unfortunately strtoul accepts these by default if they fit in the range
        return false;
    char* endp = nullptr;
    errno = 0; // strtoul will not set errno if valid
    unsigned long int n = strtoul(str.c_str(), &endp, 10);
    if (out) *out = (uint32_t)n;
    // Note that strtoul returns a *unsigned long int*, so even if it doesn't report an over/underflow
    // we still have to check that the returned value is within the range of an *uint32_t*. On 64-bit
    // platforms the size of these types may be different.
    return endp && *endp == 0 && !errno &&
           n <= std::numeric_limits<uint32_t>::max();
}

bool LegacyParseUInt8(const std::string& str, uint8_t* out)
{
    uint32_t u32;
    if (!LegacyParseUInt32(str, &u32) || u32 > std::numeric_limits<uint8_t>::max()) {
        return false;
    }
    if (out != nullptr) {
        *out = static_cast<uint8_t>(u32);
    }
    return true;
}

bool LegacyParseUInt64(const std::string& str, uint64_t* out)
{
    if (!LegacyParsePrechecks(str))
        return false;
    if (str.size() >= 1 && str[0] == '-') // Reject negative values, unfortunately strtoull accepts these by default if they fit in the range
        return false;
    char* endp = nullptr;
    errno = 0; // strtoull will not set errno if valid
    unsigned long long int n = strtoull(str.c_str(), &endp, 10);
    if (out) *out = (uint64_t)n;
    // Note that strtoull returns a *unsigned long long int*, so even if it doesn't report an over/underflow
    // we still have to check that the returned value is within the range of an *uint64_t*.
    return endp && *endp == 0 && !errno &&
           n <= std::numeric_limits<uint64_t>::max();
}

// For backwards compatibility checking.
int64_t atoi64_legacy(const std::string& str)
{
    return strtoll(str.c_str(), nullptr, 10);
}
}; // namespace

FUZZ_TARGET(string)
{
    FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
    const std::string random_string_1 = fuzzed_data_provider.ConsumeRandomLengthString(32);
    const std::string random_string_2 = fuzzed_data_provider.ConsumeRandomLengthString(32);
    const std::vector<std::string> random_string_vector = ConsumeRandomLengthStringVector(fuzzed_data_provider);

    (void)AmountErrMsg(random_string_1, random_string_2);
    (void)AmountHighWarn(random_string_1);
    BlockFilterType block_filter_type;
    (void)BlockFilterTypeByName(random_string_1, block_filter_type);
    (void)Capitalize(random_string_1);
    (void)CopyrightHolders(random_string_1);
    FeeEstimateMode fee_estimate_mode;
    (void)FeeModeFromString(random_string_1, fee_estimate_mode);
    const auto width{fuzzed_data_provider.ConsumeIntegralInRange<size_t>(1, 1000)};
    (void)FormatParagraph(random_string_1, width, fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, width));
    (void)FormatSubVersion(random_string_1, fuzzed_data_provider.ConsumeIntegral<int>(), random_string_vector);
    (void)GetDescriptorChecksum(random_string_1);
    (void)HelpExampleCli(random_string_1, random_string_2);
    (void)HelpExampleRpc(random_string_1, random_string_2);
    (void)HelpMessageGroup(random_string_1);
    (void)HelpMessageOpt(random_string_1, random_string_2);
    (void)IsDeprecatedRPCEnabled(random_string_1);
    (void)Join(random_string_vector, random_string_1);
    (void)JSONRPCError(fuzzed_data_provider.ConsumeIntegral<int>(), random_string_1);
    const util::Settings settings;
    (void)OnlyHasDefaultSectionSetting(settings, random_string_1, random_string_2);
    (void)ParseNetwork(random_string_1);
    try {
        (void)ParseNonRFCJSONValue(random_string_1);
    } catch (const std::runtime_error&) {
    }
    (void)ParseOutputType(random_string_1);
    (void)RemovePrefix(random_string_1, random_string_2);
    (void)ResolveErrMsg(random_string_1, random_string_2);
    try {
        (void)RPCConvertNamedValues(random_string_1, random_string_vector);
    } catch (const std::runtime_error&) {
    }
    try {
        (void)RPCConvertValues(random_string_1, random_string_vector);
    } catch (const std::runtime_error&) {
    }
    (void)SanitizeString(random_string_1);
    (void)SanitizeString(random_string_1, fuzzed_data_provider.ConsumeIntegralInRange<int>(0, 3));
#ifndef WIN32
    (void)ShellEscape(random_string_1);
#endif // WIN32
    uint16_t port_out;
    std::string host_out;
    SplitHostPort(random_string_1, port_out, host_out);
    (void)TimingResistantEqual(random_string_1, random_string_2);
    (void)ToLower(random_string_1);
    (void)ToUpper(random_string_1);
    (void)TrimString(random_string_1);
    (void)TrimString(random_string_1, random_string_2);
    (void)urlDecode(random_string_1);
    (void)ValidAsCString(random_string_1);
    (void)_(random_string_1.c_str());
    try {
        throw scriptnum_error{random_string_1};
    } catch (const std::runtime_error&) {
    }

    {
        CDataStream data_stream{SER_NETWORK, INIT_PROTO_VERSION};
        std::string s;
        auto limited_string = LIMITED_STRING(s, 10);
        data_stream << random_string_1;
        try {
            data_stream >> limited_string;
            assert(data_stream.empty());
            assert(s.size() <= random_string_1.size());
            assert(s.size() <= 10);
            if (!random_string_1.empty()) {
                assert(!s.empty());
            }
        } catch (const std::ios_base::failure&) {
        }
    }
    {
        CDataStream data_stream{SER_NETWORK, INIT_PROTO_VERSION};
        const auto limited_string = LIMITED_STRING(random_string_1, 10);
        data_stream << limited_string;
        std::string deserialized_string;
        data_stream >> deserialized_string;
        assert(data_stream.empty());
        assert(deserialized_string == random_string_1);
    }
    {
        int64_t amount_out;
        (void)ParseFixedPoint(random_string_1, fuzzed_data_provider.ConsumeIntegralInRange<int>(0, 1024), &amount_out);
    }
    (void)SplitString(random_string_1, fuzzed_data_provider.ConsumeIntegral<char>());
    {
        (void)Untranslated(random_string_1);
        const bilingual_str bs1{random_string_1, random_string_2};
        const bilingual_str bs2{random_string_2, random_string_1};
        (void)(bs1 + bs2);
    }
    {
        int32_t i32;
        int64_t i64;
        uint32_t u32;
        uint64_t u64;
        uint8_t u8;
        const bool ok_i32 = ParseInt32(random_string_1, &i32);
        const bool ok_i64 = ParseInt64(random_string_1, &i64);
        const bool ok_u32 = ParseUInt32(random_string_1, &u32);
        const bool ok_u64 = ParseUInt64(random_string_1, &u64);
        const bool ok_u8 = ParseUInt8(random_string_1, &u8);

        int32_t i32_legacy;
        int64_t i64_legacy;
        uint32_t u32_legacy;
        uint64_t u64_legacy;
        uint8_t u8_legacy;
        const bool ok_i32_legacy = LegacyParseInt32(random_string_1, &i32_legacy);
        const bool ok_i64_legacy = LegacyParseInt64(random_string_1, &i64_legacy);
        const bool ok_u32_legacy = LegacyParseUInt32(random_string_1, &u32_legacy);
        const bool ok_u64_legacy = LegacyParseUInt64(random_string_1, &u64_legacy);
        const bool ok_u8_legacy = LegacyParseUInt8(random_string_1, &u8_legacy);

        assert(ok_i32 == ok_i32_legacy);
        assert(ok_i64 == ok_i64_legacy);
        assert(ok_u32 == ok_u32_legacy);
        assert(ok_u64 == ok_u64_legacy);
        assert(ok_u8 == ok_u8_legacy);

        if (ok_i32) {
            assert(i32 == i32_legacy);
        }
        if (ok_i64) {
            assert(i64 == i64_legacy);
        }
        if (ok_u32) {
            assert(u32 == u32_legacy);
        }
        if (ok_u64) {
            assert(u64 == u64_legacy);
        }
        if (ok_u8) {
            assert(u8 == u8_legacy);
        }
    }

    {
        const int locale_independent_atoi_result = LocaleIndependentAtoi<int>(random_string_1);
        const int64_t atoi64_result = atoi64_legacy(random_string_1);
        assert(locale_independent_atoi_result == std::clamp<int64_t>(atoi64_result, std::numeric_limits<int>::min(), std::numeric_limits<int>::max()));
    }

    {
        const int64_t atoi64_result = atoi64_legacy(random_string_1);
        const int64_t locale_independent_atoi_result = LocaleIndependentAtoi<int64_t>(random_string_1);
        assert(atoi64_result == locale_independent_atoi_result);
    }
}
<|endoftext|>


<commit_before>#include "include/rados/librados.h"
#include "test/rados-api/test.h"

#include "gtest/gtest.h"

TEST(LibRadosIo, SimpleWrite) {
  char buf[128];
  rados_t cluster;
  rados_ioctx_t ioctx;
  std::string pool_name = get_temp_pool_name();
  ASSERT_EQ(0, create_one_pool(pool_name, &cluster));
  rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);
  memset(buf, 0xcc, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), rados_write(ioctx, "foo", buf, sizeof(buf), 0));
  rados_ioctx_destroy(ioctx);
  ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}

TEST(LibRadosIo, RoundTrip) {
  char buf[128];
  char buf2[128];
  rados_t cluster;
  rados_ioctx_t ioctx;
  std::string pool_name = get_temp_pool_name();
  ASSERT_EQ(0, create_one_pool(pool_name, &cluster));
  rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);
  memset(buf, 0xcc, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), rados_write(ioctx, "foo", buf, sizeof(buf), 0));
  memset(buf2, 0, sizeof(buf2));
  ASSERT_EQ((int)sizeof(buf2), rados_read(ioctx, "foo", buf2, sizeof(buf2), 0));
  ASSERT_EQ(0, memcmp(buf, buf2, sizeof(buf)));
  rados_ioctx_destroy(ioctx);
  ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}

TEST(LibRadosIo, OverlappingWrite) {
  char buf[128];
  char buf2[64];
  char buf3[128];
  rados_t cluster;
  rados_ioctx_t ioctx;
  std::string pool_name = get_temp_pool_name();
  ASSERT_EQ(0, create_one_pool(pool_name, &cluster));
  rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);
  memset(buf, 0xcc, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), rados_write(ioctx, "foo", buf, sizeof(buf), 0));
  memset(buf2, 0xdd, sizeof(buf2));
  ASSERT_EQ((int)sizeof(buf2), rados_write(ioctx, "foo", buf2, sizeof(buf2), 0));
  memset(buf3, 0xdd, sizeof(buf3));
  ASSERT_EQ((int)sizeof(buf3), rados_read(ioctx, "foo", buf3, sizeof(buf3), 0));
  ASSERT_EQ(0, memcmp(buf3, buf2, sizeof(buf2)));
  ASSERT_EQ(0, memcmp(buf3 + sizeof(buf2), buf, sizeof(buf) - sizeof(buf2)));
  rados_ioctx_destroy(ioctx);
  ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}
<commit_msg>test/rados-api/io: add WriteFullRoundTrip<commit_after>#include "include/rados/librados.h"
#include "test/rados-api/test.h"

#include "gtest/gtest.h"

TEST(LibRadosIo, SimpleWrite) {
  char buf[128];
  rados_t cluster;
  rados_ioctx_t ioctx;
  std::string pool_name = get_temp_pool_name();
  ASSERT_EQ(0, create_one_pool(pool_name, &cluster));
  rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);
  memset(buf, 0xcc, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), rados_write(ioctx, "foo", buf, sizeof(buf), 0));
  rados_ioctx_destroy(ioctx);
  ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}

TEST(LibRadosIo, RoundTrip) {
  char buf[128];
  char buf2[128];
  rados_t cluster;
  rados_ioctx_t ioctx;
  std::string pool_name = get_temp_pool_name();
  ASSERT_EQ(0, create_one_pool(pool_name, &cluster));
  rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);
  memset(buf, 0xcc, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), rados_write(ioctx, "foo", buf, sizeof(buf), 0));
  memset(buf2, 0, sizeof(buf2));
  ASSERT_EQ((int)sizeof(buf2), rados_read(ioctx, "foo", buf2, sizeof(buf2), 0));
  ASSERT_EQ(0, memcmp(buf, buf2, sizeof(buf)));
  rados_ioctx_destroy(ioctx);
  ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}

TEST(LibRadosIo, OverlappingWriteRoundTrip) {
  char buf[128];
  char buf2[64];
  char buf3[128];
  rados_t cluster;
  rados_ioctx_t ioctx;
  std::string pool_name = get_temp_pool_name();
  ASSERT_EQ(0, create_one_pool(pool_name, &cluster));
  rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);
  memset(buf, 0xcc, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), rados_write(ioctx, "foo", buf, sizeof(buf), 0));
  memset(buf2, 0xdd, sizeof(buf2));
  ASSERT_EQ((int)sizeof(buf2), rados_write(ioctx, "foo", buf2, sizeof(buf2), 0));
  memset(buf3, 0xdd, sizeof(buf3));
  ASSERT_EQ((int)sizeof(buf3), rados_read(ioctx, "foo", buf3, sizeof(buf3), 0));
  ASSERT_EQ(0, memcmp(buf3, buf2, sizeof(buf2)));
  ASSERT_EQ(0, memcmp(buf3 + sizeof(buf2), buf, sizeof(buf) - sizeof(buf2)));
  rados_ioctx_destroy(ioctx);
  ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}

TEST(LibRadosIo, WriteFullRoundTrip) {
  char buf[128];
  char buf2[64];
  char buf3[128];
  rados_t cluster;
  rados_ioctx_t ioctx;
  std::string pool_name = get_temp_pool_name();
  ASSERT_EQ(0, create_one_pool(pool_name, &cluster));
  rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);
  memset(buf, 0xcc, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), rados_write(ioctx, "foo", buf, sizeof(buf), 0));
  memset(buf2, 0xdd, sizeof(buf2));
  ASSERT_EQ(0, rados_write_full(ioctx, "foo", buf2, sizeof(buf2), 0));
  memset(buf3, 0xdd, sizeof(buf3));
  ASSERT_EQ((int)sizeof(buf2), rados_read(ioctx, "foo", buf3, sizeof(buf3), 0));
  ASSERT_EQ(0, memcmp(buf2, buf2, sizeof(buf2)));
  rados_ioctx_destroy(ioctx);
  ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}
<|endoftext|>


<commit_before>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *                      Eddie Hung <eddie@fpgeh.com>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

// [[CITE]] The AIGER And-Inverter Graph (AIG) Format Version 20071012
// Armin Biere. The AIGER And-Inverter Graph (AIG) Format Version 20071012. Technical Report 07/1, October 2011, FMV Reports Series, Institute for Formal Models and Verification, Johannes Kepler University, Altenbergerstr. 69, 4040 Linz, Austria.
// http://fmv.jku.at/papers/Biere-FMV-TR-07-1.pdf

#include "kernel/yosys.h"
#include "kernel/sigtools.h"
#include "aigerparse.h"

YOSYS_NAMESPACE_BEGIN

#define log_debug log

static void parse_aiger_ascii(RTLIL::Design *design, std::istream &f, std::string clk_name);
static void parse_aiger_binary(RTLIL::Design *design, std::istream &f, std::string clk_name);

void parse_aiger(RTLIL::Design *design, std::istream &f, std::string clk_name)
{
    std::string header;
    f >> header;
    if (header == "aag")
        return parse_aiger_ascii(design, f, clk_name);
    else if (header == "aig")
        return parse_aiger_binary(design, f, clk_name);
    else
        log_error("Unsupported AIGER file!\n");
}

static void parse_aiger_ascii(RTLIL::Design *design, std::istream &f, std::string clk_name)
{
    int M, I, L, O, A;
    int B=0, C=0, J=0, F=0; // Optional in AIGER 1.9
    if (!(f >> M >> I >> L >> O >> A))
        log_error("Invalid AIGER header\n");
    for (auto &i : std::array<std::reference_wrapper<int>,4>{B, C, J, F}) {
        if (f.peek() != ' ') break;
        if (!(f >> i))
            log_error("Invalid AIGER header\n");
    }

    std::string line;
    std::getline(f, line); // Ignore up to start of next ine, as standard
                           // says anything that follows could be used for
                           // optional sections

    log_debug("M=%d I=%d L=%d O=%d A=%d B=%d C=%d J=%d F=%d\n", M, I, L, O, A, B, C, J, F);

    int line_count = 1;
    std::stringstream ss;

    auto module = new RTLIL::Module;
    module->name = RTLIL::escape_id("aig"); // TODO: Name?
    if (design->module(module->name))
        log_error("Duplicate definition of module %s in line %d!\n", log_id(module->name), line_count);
    design->add(module);

    auto createWireIfNotExists = [module](int literal) {
        const int variable = literal >> 1;
        const bool invert = literal & 1;
        RTLIL::IdString wire_name(stringf("\\n%d%s", variable, invert ? "_inv" : "")); // FIXME: is "_inv" the right suffix?
        RTLIL::Wire *wire = module->wire(wire_name);
        if (wire) return wire;
        log_debug("Creating %s\n", wire_name.c_str());
        wire = module->addWire(wire_name);
        if (!invert) return wire;
        RTLIL::IdString wire_inv_name(stringf("\\n%d", variable));
        RTLIL::Wire *wire_inv = module->wire(wire_inv_name);
        if (wire_inv) {
            if (module->cell(wire_inv_name)) return wire;
        }
        else {
            log_debug("Creating %s\n", wire_inv_name.c_str());
            wire_inv = module->addWire(wire_inv_name);
        }

        log_debug("Creating %s = ~%s\n", wire_name.c_str(), wire_inv_name.c_str());
        RTLIL::Cell *inv = module->addCell(stringf("\\n%d_not", variable), "$_NOT_"); // FIXME: is "_not" the right suffix?
        inv->setPort("\\A", wire_inv);
        inv->setPort("\\Y", wire);

        return wire;
    };

    unsigned l1, l2, l3;

    // Parse inputs
    std::vector<RTLIL::Wire*> inputs;
    for (int i = 0; i < I; ++i, ++line_count) {
        if (!(f >> l1))
            log_error("Line %d cannot be interpreted as an input!\n", line_count);
        log_debug("%d is an input\n", l1);
        log_assert(!(l1 & 1)); // TODO: Inputs can't be inverted?
        RTLIL::Wire *wire = createWireIfNotExists(l1);
        wire->port_input = true;
        inputs.push_back(wire);
    }

    // Parse latches
    std::vector<RTLIL::Wire*> latches;
    RTLIL::Wire *clk_wire = nullptr;
    if (L > 0) {
        RTLIL::IdString clk_id = RTLIL::escape_id(clk_name.c_str());
        clk_wire = module->wire(clk_id);
        log_assert(!clk_wire);
        log_debug("Creating %s\n", clk_id.c_str());
        clk_wire = module->addWire(clk_id);
        clk_wire->port_input = true;
    }
    for (int i = 0; i < L; ++i, ++line_count) {
        if (!(f >> l1 >> l2))
            log_error("Line %d cannot be interpreted as a latch!\n", line_count);
        log_debug("%d %d is a latch\n", l1, l2);
        log_assert(!(l1 & 1)); // TODO: Latch outputs can't be inverted?
        RTLIL::Wire *q_wire = createWireIfNotExists(l1);
        RTLIL::Wire *d_wire = createWireIfNotExists(l2);

        module->addDff(NEW_ID, clk_wire, d_wire, q_wire);
        // AIGER latches are assumed to be initialized to zero
        q_wire->attributes["\\init"] = RTLIL::Const(0);
        latches.push_back(q_wire);
    }

    // Parse outputs
    std::vector<RTLIL::Wire*> outputs;
    for (int i = 0; i < O; ++i, ++line_count) {
        if (!(f >> l1))
            log_error("Line %d cannot be interpreted as an output!\n", line_count);

        log_debug("%d is an output\n", l1);
        RTLIL::Wire *wire = createWireIfNotExists(l1);
        wire->port_output = true;
        outputs.push_back(wire);
    }
    std::getline(f, line); // Ignore up to start of next line

    // TODO: Parse bad state properties
    for (int i = 0; i < B; ++i, ++line_count)
        std::getline(f, line); // Ignore up to start of next line

    // TODO: Parse invariant constraints
    for (int i = 0; i < C; ++i, ++line_count)
        std::getline(f, line); // Ignore up to start of next line

    // TODO: Parse justice properties
    for (int i = 0; i < J; ++i, ++line_count)
        std::getline(f, line); // Ignore up to start of next line

    // TODO: Parse fairness constraints
    for (int i = 0; i < F; ++i, ++line_count)
        std::getline(f, line); // Ignore up to start of next line

    // Parse AND
    for (int i = 0; i < A; ++i, ++line_count) {
        if (!(f >> l1 >> l2 >> l3))
            log_error("Line %d cannot be interpreted as an AND!\n", line_count);

        log_debug("%d %d %d is an AND\n", l1, l2, l3);
        log_assert(!(l1 & 1)); // TODO: Output of ANDs can't be inverted?
        RTLIL::Wire *o_wire = createWireIfNotExists(l1);
        RTLIL::Wire *i1_wire = createWireIfNotExists(l2);
        RTLIL::Wire *i2_wire = createWireIfNotExists(l3);

		RTLIL::Cell *and_cell = module->addCell(NEW_ID, "$_AND_");
		and_cell->setPort("\\A", i1_wire);
		and_cell->setPort("\\B", i2_wire);
		and_cell->setPort("\\Y", o_wire);
    }
    std::getline(f, line); // Ignore up to start of next line

    std::string s;
    for (int c = f.peek(); c != EOF; c = f.peek(), ++line_count) {
        if (c == 'i' || c == 'l' || c == 'o') {
            f.ignore(1);
            if (!(f >> l1 >> s))
                log_error("Line %d cannot be interpreted as a symbol entry!\n", line_count);

            if ((c == 'i' && l1 > inputs.size()) || (c == 'l' && l1 > latches.size()) || (c == 'o' && l1 > outputs.size()))
                log_error("Line %d has invalid symbol position!\n", line_count);

            RTLIL::Wire* wire;
            if (c == 'i') wire = inputs[l1];
            else if (c == 'l') wire = latches[l1];
            else if (c == 'o') wire = outputs[l1];
            else log_abort();

            module->rename(wire, stringf("\\%s", s.c_str()));
        }
        else if (c == 'b' || c == 'j' || c == 'f') {
            // TODO
        }
        else if (c == 'c') {
            f.ignore(1);
            if (f.peek() == '\n')
                break;
            // Else constraint (TODO)
            break;
        }
        else
            log_error("Line %d: cannot interpret first character '%c'!\n", line_count, c);
        std::getline(f, line); // Ignore up to start of next line
    }

    module->fixup_ports();
}

static void parse_aiger_binary(RTLIL::Design *design, std::istream &f, std::string clk_name)
{
}

struct AigerFrontend : public Frontend {
	AigerFrontend() : Frontend("aiger", "read AIGER file") { }
	void help() YS_OVERRIDE
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    read_aiger [options] [filename]\n");
		log("\n");
		log("Load modules from an AIGER file into the current design.\n");
		log("\n");
	}
	void execute(std::istream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
	{
		log_header(design, "Executing AIGER frontend.\n");

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++) {
			std::string arg = args[argidx];
			break;
		}
		extra_args(f, filename, args, argidx);

		parse_aiger(design, *f);
	}
} AigerFrontend;

YOSYS_NAMESPACE_END
<commit_msg>Handle reset logic in latches<commit_after>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *                      Eddie Hung <eddie@fpgeh.com>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

// [[CITE]] The AIGER And-Inverter Graph (AIG) Format Version 20071012
// Armin Biere. The AIGER And-Inverter Graph (AIG) Format Version 20071012. Technical Report 07/1, October 2011, FMV Reports Series, Institute for Formal Models and Verification, Johannes Kepler University, Altenbergerstr. 69, 4040 Linz, Austria.
// http://fmv.jku.at/papers/Biere-FMV-TR-07-1.pdf

#include "kernel/yosys.h"
#include "kernel/sigtools.h"
#include "aigerparse.h"

YOSYS_NAMESPACE_BEGIN

#define log_debug log

static void parse_aiger_ascii(RTLIL::Design *design, std::istream &f, std::string clk_name);
static void parse_aiger_binary(RTLIL::Design *design, std::istream &f, std::string clk_name);

void parse_aiger(RTLIL::Design *design, std::istream &f, std::string clk_name)
{
    std::string header;
    f >> header;
    if (header == "aag")
        return parse_aiger_ascii(design, f, clk_name);
    else if (header == "aig")
        return parse_aiger_binary(design, f, clk_name);
    else
        log_error("Unsupported AIGER file!\n");
}

static void parse_aiger_ascii(RTLIL::Design *design, std::istream &f, std::string clk_name)
{
    int M, I, L, O, A;
    int B=0, C=0, J=0, F=0; // Optional in AIGER 1.9
    if (!(f >> M >> I >> L >> O >> A))
        log_error("Invalid AIGER header\n");
    for (auto &i : std::array<std::reference_wrapper<int>,4>{B, C, J, F}) {
        if (f.peek() != ' ') break;
        if (!(f >> i))
            log_error("Invalid AIGER header\n");
    }

    std::string line;
    std::getline(f, line); // Ignore up to start of next ine, as standard
                           // says anything that follows could be used for
                           // optional sections

    log_debug("M=%d I=%d L=%d O=%d A=%d B=%d C=%d J=%d F=%d\n", M, I, L, O, A, B, C, J, F);

    int line_count = 1;
    std::stringstream ss;

    auto module = new RTLIL::Module;
    module->name = RTLIL::escape_id("aig"); // TODO: Name?
    if (design->module(module->name))
        log_error("Duplicate definition of module %s in line %d!\n", log_id(module->name), line_count);
    design->add(module);

    auto createWireIfNotExists = [module](int literal) {
        const int variable = literal >> 1;
        const bool invert = literal & 1;
        RTLIL::IdString wire_name(stringf("\\n%d%s", variable, invert ? "_inv" : "")); // FIXME: is "_inv" the right suffix?
        RTLIL::Wire *wire = module->wire(wire_name);
        if (wire) return wire;
        log_debug("Creating %s\n", wire_name.c_str());
        wire = module->addWire(wire_name);
        if (!invert) return wire;
        RTLIL::IdString wire_inv_name(stringf("\\n%d", variable));
        RTLIL::Wire *wire_inv = module->wire(wire_inv_name);
        if (wire_inv) {
            if (module->cell(wire_inv_name)) return wire;
        }
        else {
            log_debug("Creating %s\n", wire_inv_name.c_str());
            wire_inv = module->addWire(wire_inv_name);
        }

        log_debug("Creating %s = ~%s\n", wire_name.c_str(), wire_inv_name.c_str());
        RTLIL::Cell *inv = module->addCell(stringf("\\n%d_not", variable), "$_NOT_"); // FIXME: is "_not" the right suffix?
        inv->setPort("\\A", wire_inv);
        inv->setPort("\\Y", wire);

        return wire;
    };

    unsigned l1, l2, l3;

    // Parse inputs
    std::vector<RTLIL::Wire*> inputs;
    for (int i = 0; i < I; ++i, ++line_count) {
        if (!(f >> l1))
            log_error("Line %d cannot be interpreted as an input!\n", line_count);
        log_debug("%d is an input\n", l1);
        log_assert(!(l1 & 1)); // TODO: Inputs can't be inverted?
        RTLIL::Wire *wire = createWireIfNotExists(l1);
        wire->port_input = true;
        inputs.push_back(wire);
    }

    // Parse latches
    std::vector<RTLIL::Wire*> latches;
    RTLIL::Wire *clk_wire = nullptr;
    if (L > 0) {
        RTLIL::IdString clk_id = RTLIL::escape_id(clk_name.c_str());
        clk_wire = module->wire(clk_id);
        log_assert(!clk_wire);
        log_debug("Creating %s\n", clk_id.c_str());
        clk_wire = module->addWire(clk_id);
        clk_wire->port_input = true;
    }
    for (int i = 0; i < L; ++i, ++line_count) {
        if (!(f >> l1 >> l2))
            log_error("Line %d cannot be interpreted as a latch!\n", line_count);
        log_debug("%d %d is a latch\n", l1, l2);
        log_assert(!(l1 & 1)); // TODO: Latch outputs can't be inverted?
        RTLIL::Wire *q_wire = createWireIfNotExists(l1);
        RTLIL::Wire *d_wire = createWireIfNotExists(l2);

        module->addDff(NEW_ID, clk_wire, d_wire, q_wire);

        if (f.peek() == ' ') {
            if (!(f >> l3))
                log_error("Line %d cannot be interpreted as a latch!\n", line_count);

            if (l3 == 0 || l3 == 1)
                q_wire->attributes["\\init"] = RTLIL::Const(0);
            else if (l3 == l1) {
                //q_wire->attributes["\\init"] = RTLIL::Const(RTLIL::State::Sx);
            }
            else
                log_error("Line %d has invalid reset literal for latch!\n", line_count);
        }
        else {
            // AIGER latches are assumed to be initialized to zero
            q_wire->attributes["\\init"] = RTLIL::Const(0);
        }
        latches.push_back(q_wire);
    }

    // Parse outputs
    std::vector<RTLIL::Wire*> outputs;
    for (int i = 0; i < O; ++i, ++line_count) {
        if (!(f >> l1))
            log_error("Line %d cannot be interpreted as an output!\n", line_count);

        log_debug("%d is an output\n", l1);
        RTLIL::Wire *wire = createWireIfNotExists(l1);
        wire->port_output = true;
        outputs.push_back(wire);
    }
    std::getline(f, line); // Ignore up to start of next line

    // TODO: Parse bad state properties
    for (int i = 0; i < B; ++i, ++line_count)
        std::getline(f, line); // Ignore up to start of next line

    // TODO: Parse invariant constraints
    for (int i = 0; i < C; ++i, ++line_count)
        std::getline(f, line); // Ignore up to start of next line

    // TODO: Parse justice properties
    for (int i = 0; i < J; ++i, ++line_count)
        std::getline(f, line); // Ignore up to start of next line

    // TODO: Parse fairness constraints
    for (int i = 0; i < F; ++i, ++line_count)
        std::getline(f, line); // Ignore up to start of next line

    // Parse AND
    for (int i = 0; i < A; ++i, ++line_count) {
        if (!(f >> l1 >> l2 >> l3))
            log_error("Line %d cannot be interpreted as an AND!\n", line_count);

        log_debug("%d %d %d is an AND\n", l1, l2, l3);
        log_assert(!(l1 & 1)); // TODO: Output of ANDs can't be inverted?
        RTLIL::Wire *o_wire = createWireIfNotExists(l1);
        RTLIL::Wire *i1_wire = createWireIfNotExists(l2);
        RTLIL::Wire *i2_wire = createWireIfNotExists(l3);

		RTLIL::Cell *and_cell = module->addCell(NEW_ID, "$_AND_");
		and_cell->setPort("\\A", i1_wire);
		and_cell->setPort("\\B", i2_wire);
		and_cell->setPort("\\Y", o_wire);
    }
    std::getline(f, line); // Ignore up to start of next line

    std::string s;
    for (int c = f.peek(); c != EOF; c = f.peek(), ++line_count) {
        if (c == 'i' || c == 'l' || c == 'o') {
            f.ignore(1);
            if (!(f >> l1 >> s))
                log_error("Line %d cannot be interpreted as a symbol entry!\n", line_count);

            if ((c == 'i' && l1 > inputs.size()) || (c == 'l' && l1 > latches.size()) || (c == 'o' && l1 > outputs.size()))
                log_error("Line %d has invalid symbol position!\n", line_count);

            RTLIL::Wire* wire;
            if (c == 'i') wire = inputs[l1];
            else if (c == 'l') wire = latches[l1];
            else if (c == 'o') wire = outputs[l1];
            else log_abort();

            module->rename(wire, stringf("\\%s", s.c_str()));
        }
        else if (c == 'b' || c == 'j' || c == 'f') {
            // TODO
        }
        else if (c == 'c') {
            f.ignore(1);
            if (f.peek() == '\n')
                break;
            // Else constraint (TODO)
            break;
        }
        else
            log_error("Line %d: cannot interpret first character '%c'!\n", line_count, c);
        std::getline(f, line); // Ignore up to start of next line
    }

    module->fixup_ports();
}

static void parse_aiger_binary(RTLIL::Design *design, std::istream &f, std::string clk_name)
{
}

struct AigerFrontend : public Frontend {
	AigerFrontend() : Frontend("aiger", "read AIGER file") { }
	void help() YS_OVERRIDE
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    read_aiger [options] [filename]\n");
		log("\n");
		log("Load modules from an AIGER file into the current design.\n");
		log("\n");
	}
	void execute(std::istream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
	{
		log_header(design, "Executing AIGER frontend.\n");

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++) {
			std::string arg = args[argidx];
			break;
		}
		extra_args(f, filename, args, argidx);

		parse_aiger(design, *f);
	}
} AigerFrontend;

YOSYS_NAMESPACE_END
<|endoftext|>


<commit_before>#include <complex>
#include "functions/trig.hh"
#include "functions/full_function_defs.hh"
#include "pointwise_equal.hh"
#include "functions/all_simplifications.hh"
#include <boost/test/unit_test.hpp>
#include <limits>

BOOST_AUTO_TEST_CASE(trig_tests) {
  using namespace manifolds;
  Sin s;
  Cos c;
  Tan t;

  PointwiseEqual(s, [](auto x) { return std::sin(std::get<0>(x)); });
  PointwiseEqual(c, [](auto x) { return std::cos(std::get<0>(x)); });
  PointwiseEqual(t, [](auto x) { return std::tan(std::get<0>(x)); });

  Sinh sh;
  Cosh ch;
  Tanh th;

  PointwiseEqual(sh, [](auto x) { return std::sinh(std::get<0>(x)); });
  PointwiseEqual(ch, [](auto x) { return std::cosh(std::get<0>(x)); });
  PointwiseEqual(th, [](auto x) { return std::tanh(std::get<0>(x)); });

  std::complex<double> i(0, 1);
  BOOST_CHECK_EQUAL(std::abs(s(i)), sh(1));
  BOOST_CHECK_EQUAL(std::abs(sh(i)), s(1));
  ACos ac;
  ASin as;
  ATan at;
  double min = -0.9999;
  double max = -min;
  PointwiseEqual(as, [](auto x) { return std::asin(std::get<0>(x)); }, 100, 0,
                 min, max);
  PointwiseEqual(ac, [](auto x) { return std::acos(std::get<0>(x)); }, 100, 0,
                 min, max);
  PointwiseEqual(at, [](auto x) { return std::atan(std::get<0>(x)); }, 100, 0,
                 min, max);

  ACosh ach;
  ASinh ash;
  ATanh ath;

  PointwiseEqual(ash, [](auto x) { return std::asinh(std::get<0>(x)); }, 100,
                 0);
  PointwiseEqual(ach, [](auto x) { return std::acosh(std::get<0>(x)); }, 100, 0,
                 1, 25);
  PointwiseEqual(ath, [](auto x) { return std::atanh(std::get<0>(x)); }, 100, 0,
                 min, max);

  BOOST_CHECK_EQUAL(Simplify(ACos()(Cos())(x)), x);
  BOOST_CHECK_EQUAL(Simplify(ASin()(Sin())(x)), x);
  BOOST_CHECK_EQUAL(Simplify(ATan()(Tan())(x)), x);

  BOOST_CHECK_EQUAL(Simplify(ACosh()(Cosh())(x)), x);
  BOOST_CHECK_EQUAL(Simplify(ASinh()(Sinh())(x)), x);
  BOOST_CHECK_EQUAL(Simplify(ATanh()(Tanh())(x)), x);
}
<commit_msg>Testing simplifications of trig expressions<commit_after>#include <complex>
#include "functions/trig.hh"
#include "functions/full_function_defs.hh"
#include "pointwise_equal.hh"
#include "functions/all_simplifications.hh"
#include <boost/test/unit_test.hpp>
#include "functions/operators.hh"
#include <limits>

BOOST_AUTO_TEST_CASE(trig_tests) {
  using namespace manifolds;
  Sin s;
  Cos c;
  Tan t;

  PointwiseEqual(s, [](auto x) { return std::sin(std::get<0>(x)); });
  PointwiseEqual(c, [](auto x) { return std::cos(std::get<0>(x)); });
  PointwiseEqual(t, [](auto x) { return std::tan(std::get<0>(x)); });

  Sinh sh;
  Cosh ch;
  Tanh th;

  PointwiseEqual(sh, [](auto x) { return std::sinh(std::get<0>(x)); });
  PointwiseEqual(ch, [](auto x) { return std::cosh(std::get<0>(x)); });
  PointwiseEqual(th, [](auto x) { return std::tanh(std::get<0>(x)); });

  std::complex<double> i(0, 1);
  BOOST_CHECK_EQUAL(std::abs(s(i)), sh(1));
  BOOST_CHECK_EQUAL(std::abs(sh(i)), s(1));
  ACos ac;
  ASin as;
  ATan at;
  double min = -0.9999;
  double max = -min;
  PointwiseEqual(as, [](auto x) { return std::asin(std::get<0>(x)); }, 100, 0,
                 min, max);
  PointwiseEqual(ac, [](auto x) { return std::acos(std::get<0>(x)); }, 100, 0,
                 min, max);
  PointwiseEqual(at, [](auto x) { return std::atan(std::get<0>(x)); }, 100, 0,
                 min, max);

  ACosh ach;
  ASinh ash;
  ATanh ath;

  PointwiseEqual(ash, [](auto x) { return std::asinh(std::get<0>(x)); }, 100,
                 0);
  PointwiseEqual(ach, [](auto x) { return std::acosh(std::get<0>(x)); }, 100, 0,
                 1, 25);
  PointwiseEqual(ath, [](auto x) { return std::atanh(std::get<0>(x)); }, 100, 0,
                 min, max);

  BOOST_CHECK_EQUAL(Simplify(ACos()(Cos())(x)), x);
  BOOST_CHECK_EQUAL(Simplify(ASin()(Sin())(x)), x);
  BOOST_CHECK_EQUAL(Simplify(ATan()(Tan())(x)), x);

  BOOST_CHECK_EQUAL(Simplify(ACosh()(Cosh())(x)), x);
  BOOST_CHECK_EQUAL(Simplify(ASinh()(Sinh())(x)), x);
  BOOST_CHECK_EQUAL(Simplify(ATanh()(Tanh())(x)), x);
  static_assert(is_all_but_last_0<0,0,2>::value, "");

  BOOST_CHECK_EQUAL(Simplify(Sin()(GetIPolynomial<0,-2>())(x)),
                    (GetIPolynomial<0,-2>()((Sin()*Cos()))(x)));
  BOOST_CHECK_EQUAL(Simplify(Cos()(GetIPolynomial<0,-2>())(x)),
                    (Cos()*Cos()-Sin()*Sin())(x));
  auto p = Simplify(Sin()(GetIPolynomial<0,3>()(x)));
  std::cout << get_cpp_name<decltype(p)>() << '\n';
  std::cout << '\n' << p << '\n';
}
<|endoftext|>