<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_comphelper.hxx"

#include <com/sun/star/lang/XMultiComponentFactory.hpp>
#include <com/sun/star/awt/XRequestCallback.hpp>
#include <com/sun/star/frame/XDesktop.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>

#include <comphelper_module.hxx>
#include "officerestartmanager.hxx"

using namespace ::com::sun::star;

namespace comphelper
{

// ----------------------------------------------------------
uno::Sequence< ::rtl::OUString > SAL_CALL OOfficeRestartManager::getSupportedServiceNames_static()
{
    uno::Sequence< rtl::OUString > aResult( 1 );
    aResult[0] = getServiceName_static();
    return aResult;
}

// ----------------------------------------------------------
::rtl::OUString SAL_CALL OOfficeRestartManager::getImplementationName_static()
{
    return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.task.OfficeRestartManager" ) );
}

// ----------------------------------------------------------
::rtl::OUString SAL_CALL OOfficeRestartManager::getSingletonName_static()
{
    return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.task.OfficeRestartManager" ) );
}

// ----------------------------------------------------------
::rtl::OUString SAL_CALL OOfficeRestartManager::getServiceName_static()
{
    return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.task.OfficeRestartManager" ) );
}

// ----------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL OOfficeRestartManager::Create( const uno::Reference< uno::XComponentContext >& rxContext )
{
    return static_cast< cppu::OWeakObject* >( new OOfficeRestartManager( rxContext ) );
}

// XRestartManager
// ----------------------------------------------------------
void SAL_CALL OOfficeRestartManager::requestRestart( const uno::Reference< task::XInteractionHandler >& /* xInteractionHandler */ )
    throw (uno::Exception, uno::RuntimeException)
{
    if ( !m_xContext.is() )
        throw uno::RuntimeException();

    {
        ::osl::MutexGuard aGuard( m_aMutex );

        // if the restart already running there is no need to trigger it again
        if ( m_bRestartRequested )
            return;
#ifndef MACOSX
        m_bRestartRequested = sal_True;
#endif
        // the office is still not initialized, no need to terminate, changing the state is enough
        if ( !m_bOfficeInitialized )
            return;
    }

    // TODO: use InteractionHandler to report errors
    try
    {
        // register itself as a job that should be executed asynchronously
        uno::Reference< lang::XMultiComponentFactory > xFactory( m_xContext->getServiceManager(), uno::UNO_SET_THROW );

        uno::Reference< awt::XRequestCallback > xRequestCallback(
            xFactory->createInstanceWithContext(
                 ::rtl::OUString::createFromAscii("com.sun.star.awt.AsyncCallback"),
                 m_xContext ),
             uno::UNO_QUERY_THROW );

        xRequestCallback->addCallback( this, uno::Any() );
    }
    catch ( uno::Exception& )
    {
        // the try to request restart has failed
        m_bRestartRequested = sal_False;
    }
}

// ----------------------------------------------------------
::sal_Bool SAL_CALL OOfficeRestartManager::isRestartRequested( ::sal_Bool bOfficeInitialized )
    throw (uno::Exception, uno::RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );

    if ( bOfficeInitialized && !m_bOfficeInitialized )
        m_bOfficeInitialized = bOfficeInitialized;

    return m_bRestartRequested;
}

// XCallback
// ----------------------------------------------------------
void SAL_CALL OOfficeRestartManager::notify( const uno::Any& /* aData */ )
    throw ( uno::RuntimeException )
{
    try
    {
        sal_Bool bSuccess = sal_False;

        if ( m_xContext.is() )
        {
            uno::Reference< lang::XMultiComponentFactory > xFactory( m_xContext->getServiceManager(), uno::UNO_SET_THROW );
            uno::Reference< frame::XDesktop > xDesktop(
                xFactory->createInstanceWithContext(
                    ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.frame.Desktop" ) ), m_xContext ),
                uno::UNO_QUERY_THROW );

            // Turn Quickstarter veto off
            uno::Reference< beans::XPropertySet > xPropertySet( xDesktop, uno::UNO_QUERY_THROW );
            ::rtl::OUString aVetoPropName( RTL_CONSTASCII_USTRINGPARAM( "SuspendQuickstartVeto" ) );
            uno::Any aValue;
            aValue <<= (sal_Bool)sal_True;
            xPropertySet->setPropertyValue( aVetoPropName, aValue );

            try
            {
                bSuccess = xDesktop->terminate();
            } catch( uno::Exception& )
            {}

            if ( !bSuccess )
            {
                aValue <<= (sal_Bool)sal_False;
                xPropertySet->setPropertyValue( aVetoPropName, aValue );
            }
        }

        if ( !bSuccess )
            m_bRestartRequested = sal_False;
    }
    catch( uno::Exception& )
    {
        // the try to restart has failed
        m_bRestartRequested = sal_False;
    }
}

// XServiceInfo
// ----------------------------------------------------------
::rtl::OUString SAL_CALL OOfficeRestartManager::getImplementationName() throw (uno::RuntimeException)
{
    return getImplementationName_static();
}

// ----------------------------------------------------------
::sal_Bool SAL_CALL OOfficeRestartManager::supportsService( const ::rtl::OUString& aServiceName ) throw (uno::RuntimeException)
{
    const uno::Sequence< rtl::OUString > & aSupportedNames = getSupportedServiceNames_static();
    for ( sal_Int32 nInd = 0; nInd < aSupportedNames.getLength(); nInd++ )
    {
        if ( aSupportedNames[ nInd ].equals( aServiceName ) )
            return sal_True;
    }

    return sal_False;
}

// ----------------------------------------------------------
uno::Sequence< ::rtl::OUString > SAL_CALL OOfficeRestartManager::getSupportedServiceNames() throw (uno::RuntimeException)
{
    return getSupportedServiceNames_static();
}

} // namespace comphelper

void createRegistryInfo_OOfficeRestartManager()
{
    static ::comphelper::module::OAutoRegistration< ::comphelper::OOfficeRestartManager > aAutoRegistration;
    static ::comphelper::module::OSingletonRegistration< ::comphelper::OOfficeRestartManager > aSingletonRegistration;
}
<commit_msg>jl154: Local merge<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_comphelper.hxx"

#include <com/sun/star/lang/XMultiComponentFactory.hpp>
#include <com/sun/star/awt/XRequestCallback.hpp>
#include <com/sun/star/frame/XDesktop.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>

#include <comphelper_module.hxx>
#include "officerestartmanager.hxx"

using namespace ::com::sun::star;

namespace comphelper
{

// ----------------------------------------------------------
uno::Sequence< ::rtl::OUString > SAL_CALL OOfficeRestartManager::getSupportedServiceNames_static()
{
    uno::Sequence< rtl::OUString > aResult( 1 );
    aResult[0] = getServiceName_static();
    return aResult;
}

// ----------------------------------------------------------
::rtl::OUString SAL_CALL OOfficeRestartManager::getImplementationName_static()
{
    return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.task.OfficeRestartManager" ) );
}

// ----------------------------------------------------------
::rtl::OUString SAL_CALL OOfficeRestartManager::getSingletonName_static()
{
    return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.task.OfficeRestartManager" ) );
}

// ----------------------------------------------------------
::rtl::OUString SAL_CALL OOfficeRestartManager::getServiceName_static()
{
    return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.task.OfficeRestartManager" ) );
}

// ----------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL OOfficeRestartManager::Create( const uno::Reference< uno::XComponentContext >& rxContext )
{
    return static_cast< cppu::OWeakObject* >( new OOfficeRestartManager( rxContext ) );
}

// XRestartManager
// ----------------------------------------------------------
void SAL_CALL OOfficeRestartManager::requestRestart( const uno::Reference< task::XInteractionHandler >& /* xInteractionHandler */ )
    throw (uno::Exception, uno::RuntimeException)
{
    if ( !m_xContext.is() )
        throw uno::RuntimeException();

    {
        ::osl::MutexGuard aGuard( m_aMutex );

        // if the restart already running there is no need to trigger it again
        if ( m_bRestartRequested )
            return;

        m_bRestartRequested = sal_True;

        // the office is still not initialized, no need to terminate, changing the state is enough
        if ( !m_bOfficeInitialized )
            return;
    }

    // TODO: use InteractionHandler to report errors
    try
    {
        // register itself as a job that should be executed asynchronously
        uno::Reference< lang::XMultiComponentFactory > xFactory( m_xContext->getServiceManager(), uno::UNO_SET_THROW );

        uno::Reference< awt::XRequestCallback > xRequestCallback(
            xFactory->createInstanceWithContext(
                 ::rtl::OUString::createFromAscii("com.sun.star.awt.AsyncCallback"),
                 m_xContext ),
             uno::UNO_QUERY_THROW );

        xRequestCallback->addCallback( this, uno::Any() );
    }
    catch ( uno::Exception& )
    {
        // the try to request restart has failed
        m_bRestartRequested = sal_False;
    }
}

// ----------------------------------------------------------
::sal_Bool SAL_CALL OOfficeRestartManager::isRestartRequested( ::sal_Bool bOfficeInitialized )
    throw (uno::Exception, uno::RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );

    if ( bOfficeInitialized && !m_bOfficeInitialized )
        m_bOfficeInitialized = bOfficeInitialized;

    return m_bRestartRequested;
}

// XCallback
// ----------------------------------------------------------
void SAL_CALL OOfficeRestartManager::notify( const uno::Any& /* aData */ )
    throw ( uno::RuntimeException )
{
    try
    {
        sal_Bool bSuccess = sal_False;

        if ( m_xContext.is() )
        {
            uno::Reference< lang::XMultiComponentFactory > xFactory( m_xContext->getServiceManager(), uno::UNO_SET_THROW );
            uno::Reference< frame::XDesktop > xDesktop(
                xFactory->createInstanceWithContext(
                    ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.frame.Desktop" ) ), m_xContext ),
                uno::UNO_QUERY_THROW );

            // Turn Quickstarter veto off
            uno::Reference< beans::XPropertySet > xPropertySet( xDesktop, uno::UNO_QUERY_THROW );
            ::rtl::OUString aVetoPropName( RTL_CONSTASCII_USTRINGPARAM( "SuspendQuickstartVeto" ) );
            uno::Any aValue;
            aValue <<= (sal_Bool)sal_True;
            xPropertySet->setPropertyValue( aVetoPropName, aValue );

            try
            {
                bSuccess = xDesktop->terminate();
            } catch( uno::Exception& )
            {}

            if ( !bSuccess )
            {
                aValue <<= (sal_Bool)sal_False;
                xPropertySet->setPropertyValue( aVetoPropName, aValue );
            }
        }

        if ( !bSuccess )
            m_bRestartRequested = sal_False;
    }
    catch( uno::Exception& )
    {
        // the try to restart has failed
        m_bRestartRequested = sal_False;
    }
}

// XServiceInfo
// ----------------------------------------------------------
::rtl::OUString SAL_CALL OOfficeRestartManager::getImplementationName() throw (uno::RuntimeException)
{
    return getImplementationName_static();
}

// ----------------------------------------------------------
::sal_Bool SAL_CALL OOfficeRestartManager::supportsService( const ::rtl::OUString& aServiceName ) throw (uno::RuntimeException)
{
    const uno::Sequence< rtl::OUString > & aSupportedNames = getSupportedServiceNames_static();
    for ( sal_Int32 nInd = 0; nInd < aSupportedNames.getLength(); nInd++ )
    {
        if ( aSupportedNames[ nInd ].equals( aServiceName ) )
            return sal_True;
    }

    return sal_False;
}

// ----------------------------------------------------------
uno::Sequence< ::rtl::OUString > SAL_CALL OOfficeRestartManager::getSupportedServiceNames() throw (uno::RuntimeException)
{
    return getSupportedServiceNames_static();
}

} // namespace comphelper

void createRegistryInfo_OOfficeRestartManager()
{
    static ::comphelper::module::OAutoRegistration< ::comphelper::OOfficeRestartManager > aAutoRegistration;
    static ::comphelper::module::OSingletonRegistration< ::comphelper::OOfficeRestartManager > aSingletonRegistration;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: DIndexColumns.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: obo $ $Date: 2006-07-10 14:35:42 $
 *
 *  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 _CONNECTIVITY_DBASE_INDEXCOLUMNS_HXX_
#define _CONNECTIVITY_DBASE_INDEXCOLUMNS_HXX_

#ifndef _CONNECTIVITY_SDBCX_COLLECTION_HXX_
#include "connectivity/sdbcx/VCollection.hxx"
#endif
#ifndef _CONNECTIVITY_DBASE_INDEX_HXX_
#include "dbase/DIndex.hxx"
#endif
#ifndef _CONNECTIVITY_DBASE_TABLE_HXX_
#include "dbase/DTable.hxx"
#endif

namespace connectivity
{
    namespace dbase
    {
        class ODbaseIndexColumns : public sdbcx::OCollection
        {
            ODbaseIndex* m_pIndex;
        protected:
            virtual sdbcx::ObjectType createObject(const ::rtl::OUString& _rName);
            virtual void impl_refresh() throw(::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > createDescriptor();
            virtual sdbcx::ObjectType appendObject( const ::rtl::OUString& _rForName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& descriptor );
        public:
            ODbaseIndexColumns( ODbaseIndex* _pIndex,
                                ::osl::Mutex& _rMutex,
                                const TStringVector &_rVector)
                        : sdbcx::OCollection(*_pIndex,_pIndex->getTable()->getConnection()->getMetaData()->storesMixedCaseQuotedIdentifiers(),_rMutex,_rVector)
                        , m_pIndex(_pIndex)
            {}

        };
    }
}
#endif // _CONNECTIVITY_DBASE_INDEXCOLUMNS_HXX_

<commit_msg>INTEGRATION: CWS changefileheader (1.8.262); FILE MERGED 2008/04/01 10:53:25 thb 1.8.262.2: #i85898# Stripping all external header guards 2008/03/28 15:24:18 rt 1.8.262.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: DIndexColumns.hxx,v $
 * $Revision: 1.9 $
 *
 * 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 _CONNECTIVITY_DBASE_INDEXCOLUMNS_HXX_
#define _CONNECTIVITY_DBASE_INDEXCOLUMNS_HXX_

#include "connectivity/sdbcx/VCollection.hxx"
#include "dbase/DIndex.hxx"
#include "dbase/DTable.hxx"

namespace connectivity
{
    namespace dbase
    {
        class ODbaseIndexColumns : public sdbcx::OCollection
        {
            ODbaseIndex* m_pIndex;
        protected:
            virtual sdbcx::ObjectType createObject(const ::rtl::OUString& _rName);
            virtual void impl_refresh() throw(::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > createDescriptor();
            virtual sdbcx::ObjectType appendObject( const ::rtl::OUString& _rForName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& descriptor );
        public:
            ODbaseIndexColumns( ODbaseIndex* _pIndex,
                                ::osl::Mutex& _rMutex,
                                const TStringVector &_rVector)
                        : sdbcx::OCollection(*_pIndex,_pIndex->getTable()->getConnection()->getMetaData()->storesMixedCaseQuotedIdentifiers(),_rMutex,_rVector)
                        , m_pIndex(_pIndex)
            {}

        };
    }
}
#endif // _CONNECTIVITY_DBASE_INDEXCOLUMNS_HXX_

<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/public/test/mock_render_process_host.h"

#include "base/lazy_instance.h"
#include "base/message_loop/message_loop.h"
#include "base/time/time.h"
#include "content/browser/child_process_security_policy_impl.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/common/child_process_host_impl.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/render_widget_host_iterator.h"
#include "content/public/browser/storage_partition.h"

namespace content {

MockRenderProcessHost::MockRenderProcessHost(BrowserContext* browser_context)
    : transport_dib_(NULL),
      bad_msg_count_(0),
      factory_(NULL),
      id_(ChildProcessHostImpl::GenerateChildProcessUniqueId()),
      browser_context_(browser_context),
      prev_routing_id_(0),
      fast_shutdown_started_(false),
      deletion_callback_called_(false),
      is_guest_(false) {
  // Child process security operations can't be unit tested unless we add
  // ourselves as an existing child process.
  ChildProcessSecurityPolicyImpl::GetInstance()->Add(GetID());

  RenderProcessHostImpl::RegisterHost(GetID(), this);
}

MockRenderProcessHost::~MockRenderProcessHost() {
  ChildProcessSecurityPolicyImpl::GetInstance()->Remove(GetID());
  delete transport_dib_;
  if (factory_)
    factory_->Remove(this);

  // In unit tests, Cleanup() might not have been called.
  if (!deletion_callback_called_) {
    FOR_EACH_OBSERVER(RenderProcessHostObserver,
                      observers_,
                      RenderProcessHostDestroyed(this));
    RenderProcessHostImpl::UnregisterHost(GetID());
  }
}

void MockRenderProcessHost::EnableSendQueue() {
}

bool MockRenderProcessHost::Init() {
  return true;
}

int MockRenderProcessHost::GetNextRoutingID() {
  return ++prev_routing_id_;
}

void MockRenderProcessHost::AddRoute(
    int32 routing_id,
    IPC::Listener* listener) {
  listeners_.AddWithID(listener, routing_id);
}

void MockRenderProcessHost::RemoveRoute(int32 routing_id) {
  DCHECK(listeners_.Lookup(routing_id) != NULL);
  listeners_.Remove(routing_id);
  Cleanup();
}

void MockRenderProcessHost::AddObserver(RenderProcessHostObserver* observer) {
  observers_.AddObserver(observer);
}

void MockRenderProcessHost::RemoveObserver(
    RenderProcessHostObserver* observer) {
  observers_.RemoveObserver(observer);
}

bool MockRenderProcessHost::WaitForBackingStoreMsg(
    int render_widget_id,
    const base::TimeDelta& max_delay,
    IPC::Message* msg) {
  return false;
}

void MockRenderProcessHost::ReceivedBadMessage() {
  ++bad_msg_count_;
}

void MockRenderProcessHost::WidgetRestored() {
}

void MockRenderProcessHost::WidgetHidden() {
}

int MockRenderProcessHost::VisibleWidgetCount() const {
  return 1;
}

bool MockRenderProcessHost::IsGuest() const {
  return is_guest_;
}

StoragePartition* MockRenderProcessHost::GetStoragePartition() const {
  return NULL;
}

void MockRenderProcessHost::AddWord(const base::string16& word) {
}

bool MockRenderProcessHost::FastShutdownIfPossible() {
  // We aren't actually going to do anything, but set |fast_shutdown_started_|
  // to true so that tests know we've been called.
  fast_shutdown_started_ = true;
  return true;
}

bool MockRenderProcessHost::FastShutdownStarted() const {
  return fast_shutdown_started_;
}

void MockRenderProcessHost::DumpHandles() {
}

base::ProcessHandle MockRenderProcessHost::GetHandle() const {
  // Return the current-process handle for the IPC::GetFileHandleForProcess
  // function.
  return base::Process::Current().handle();
}

bool MockRenderProcessHost::Send(IPC::Message* msg) {
  // Save the message in the sink.
  sink_.OnMessageReceived(*msg);
  delete msg;
  return true;
}

TransportDIB* MockRenderProcessHost::MapTransportDIB(TransportDIB::Id dib_id) {
#if defined(OS_WIN)
  HANDLE duped;
  DuplicateHandle(GetCurrentProcess(), dib_id.handle, GetCurrentProcess(),
                  &duped, 0, TRUE, DUPLICATE_SAME_ACCESS);
  return TransportDIB::Map(duped);
#elif defined(TOOLKIT_GTK)
  return TransportDIB::Map(dib_id.shmkey);
#elif defined(OS_ANDROID)
  // On Android, Handles and Ids are the same underlying type.
  return TransportDIB::Map(dib_id);
#else
  // On POSIX, TransportDIBs are always created in the browser, so we cannot map
  // one from a dib_id.
  return TransportDIB::Create(100 * 100 * 4, 0);
#endif
}

TransportDIB* MockRenderProcessHost::GetTransportDIB(TransportDIB::Id dib_id) {
  if (transport_dib_)
    return transport_dib_;

  transport_dib_ = MapTransportDIB(dib_id);
  return transport_dib_;
}

int MockRenderProcessHost::GetID() const {
  return id_;
}

bool MockRenderProcessHost::HasConnection() const {
  return true;
}

void MockRenderProcessHost::SetIgnoreInputEvents(bool ignore_input_events) {
}

bool MockRenderProcessHost::IgnoreInputEvents() const {
  return false;
}

void MockRenderProcessHost::Cleanup() {
  if (listeners_.IsEmpty()) {
    FOR_EACH_OBSERVER(RenderProcessHostObserver,
                      observers_,
                      RenderProcessHostDestroyed(this));
    NotificationService::current()->Notify(
        NOTIFICATION_RENDERER_PROCESS_TERMINATED,
        Source<RenderProcessHost>(this),
        NotificationService::NoDetails());
    base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
    RenderProcessHostImpl::UnregisterHost(GetID());
    deletion_callback_called_ = true;
  }
}

void MockRenderProcessHost::AddPendingView() {
}

void MockRenderProcessHost::RemovePendingView() {
}

void MockRenderProcessHost::SetSuddenTerminationAllowed(bool allowed) {
}

bool MockRenderProcessHost::SuddenTerminationAllowed() const {
  return true;
}

BrowserContext* MockRenderProcessHost::GetBrowserContext() const {
  return browser_context_;
}

bool MockRenderProcessHost::InSameStoragePartition(
    StoragePartition* partition) const {
  // Mock RPHs only have one partition.
  return true;
}

IPC::ChannelProxy* MockRenderProcessHost::GetChannel() {
  return NULL;
}

void MockRenderProcessHost::AddFilter(BrowserMessageFilter* filter) {
}

int MockRenderProcessHost::GetActiveViewCount() {
  int num_active_views = 0;
  scoped_ptr<RenderWidgetHostIterator> widgets(
      RenderWidgetHost::GetRenderWidgetHosts());
  while (RenderWidgetHost* widget = widgets->GetNextHost()) {
    // Count only RenderWidgetHosts in this process.
    if (widget->GetProcess()->GetID() == GetID())
      num_active_views++;
  }
  return num_active_views;
}

bool MockRenderProcessHost::FastShutdownForPageCount(size_t count) {
  if (static_cast<size_t>(GetActiveViewCount()) == count)
    return FastShutdownIfPossible();
  return false;
}

base::TimeDelta MockRenderProcessHost::GetChildProcessIdleTime() const {
  return base::TimeDelta::FromMilliseconds(0);
}

void MockRenderProcessHost::SurfaceUpdated(int32 surface_id) {
}

void MockRenderProcessHost::ResumeRequestsForView(int route_id) {
}

void MockRenderProcessHost::FilterURL(bool empty_allowed, GURL* url) {
  RenderProcessHostImpl::FilterURL(this, empty_allowed, url);
}

#if defined(ENABLE_WEBRTC)
void MockRenderProcessHost::EnableAecDump(const base::FilePath& file) {
}

void MockRenderProcessHost::DisableAecDump() {
}
#endif

bool MockRenderProcessHost::OnMessageReceived(const IPC::Message& msg) {
  IPC::Listener* listener = listeners_.Lookup(msg.routing_id());
  if (listener)
    return listener->OnMessageReceived(msg);
  return false;
}

void MockRenderProcessHost::OnChannelConnected(int32 peer_pid) {
}

MockRenderProcessHostFactory::MockRenderProcessHostFactory() {}

MockRenderProcessHostFactory::~MockRenderProcessHostFactory() {
  // Detach this object from MockRenderProcesses to prevent STLDeleteElements()
  // from calling MockRenderProcessHostFactory::Remove().
  for (ScopedVector<MockRenderProcessHost>::iterator it = processes_.begin();
       it != processes_.end(); ++it) {
    (*it)->SetFactory(NULL);
  }
}

RenderProcessHost* MockRenderProcessHostFactory::CreateRenderProcessHost(
    BrowserContext* browser_context,
    SiteInstance* site_instance) const {
  MockRenderProcessHost* host = new MockRenderProcessHost(browser_context);
  if (host) {
    processes_.push_back(host);
    host->SetFactory(this);
  }
  return host;
}

void MockRenderProcessHostFactory::Remove(MockRenderProcessHost* host) const {
  for (ScopedVector<MockRenderProcessHost>::iterator it = processes_.begin();
       it != processes_.end(); ++it) {
    if (*it == host) {
      processes_.weak_erase(it);
      break;
    }
  }
}

}  // content
<commit_msg>Switch MockRenderProcessHost to only fire observers rather than use notifications.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/public/test/mock_render_process_host.h"

#include "base/lazy_instance.h"
#include "base/message_loop/message_loop.h"
#include "base/time/time.h"
#include "content/browser/child_process_security_policy_impl.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/common/child_process_host_impl.h"
#include "content/public/browser/render_widget_host_iterator.h"
#include "content/public/browser/storage_partition.h"

namespace content {

MockRenderProcessHost::MockRenderProcessHost(BrowserContext* browser_context)
    : transport_dib_(NULL),
      bad_msg_count_(0),
      factory_(NULL),
      id_(ChildProcessHostImpl::GenerateChildProcessUniqueId()),
      browser_context_(browser_context),
      prev_routing_id_(0),
      fast_shutdown_started_(false),
      deletion_callback_called_(false),
      is_guest_(false) {
  // Child process security operations can't be unit tested unless we add
  // ourselves as an existing child process.
  ChildProcessSecurityPolicyImpl::GetInstance()->Add(GetID());

  RenderProcessHostImpl::RegisterHost(GetID(), this);
}

MockRenderProcessHost::~MockRenderProcessHost() {
  ChildProcessSecurityPolicyImpl::GetInstance()->Remove(GetID());
  delete transport_dib_;
  if (factory_)
    factory_->Remove(this);

  // In unit tests, Cleanup() might not have been called.
  if (!deletion_callback_called_) {
    FOR_EACH_OBSERVER(RenderProcessHostObserver,
                      observers_,
                      RenderProcessHostDestroyed(this));
    RenderProcessHostImpl::UnregisterHost(GetID());
  }
}

void MockRenderProcessHost::EnableSendQueue() {
}

bool MockRenderProcessHost::Init() {
  return true;
}

int MockRenderProcessHost::GetNextRoutingID() {
  return ++prev_routing_id_;
}

void MockRenderProcessHost::AddRoute(
    int32 routing_id,
    IPC::Listener* listener) {
  listeners_.AddWithID(listener, routing_id);
}

void MockRenderProcessHost::RemoveRoute(int32 routing_id) {
  DCHECK(listeners_.Lookup(routing_id) != NULL);
  listeners_.Remove(routing_id);
  Cleanup();
}

void MockRenderProcessHost::AddObserver(RenderProcessHostObserver* observer) {
  observers_.AddObserver(observer);
}

void MockRenderProcessHost::RemoveObserver(
    RenderProcessHostObserver* observer) {
  observers_.RemoveObserver(observer);
}

bool MockRenderProcessHost::WaitForBackingStoreMsg(
    int render_widget_id,
    const base::TimeDelta& max_delay,
    IPC::Message* msg) {
  return false;
}

void MockRenderProcessHost::ReceivedBadMessage() {
  ++bad_msg_count_;
}

void MockRenderProcessHost::WidgetRestored() {
}

void MockRenderProcessHost::WidgetHidden() {
}

int MockRenderProcessHost::VisibleWidgetCount() const {
  return 1;
}

bool MockRenderProcessHost::IsGuest() const {
  return is_guest_;
}

StoragePartition* MockRenderProcessHost::GetStoragePartition() const {
  return NULL;
}

void MockRenderProcessHost::AddWord(const base::string16& word) {
}

bool MockRenderProcessHost::FastShutdownIfPossible() {
  // We aren't actually going to do anything, but set |fast_shutdown_started_|
  // to true so that tests know we've been called.
  fast_shutdown_started_ = true;
  return true;
}

bool MockRenderProcessHost::FastShutdownStarted() const {
  return fast_shutdown_started_;
}

void MockRenderProcessHost::DumpHandles() {
}

base::ProcessHandle MockRenderProcessHost::GetHandle() const {
  // Return the current-process handle for the IPC::GetFileHandleForProcess
  // function.
  return base::Process::Current().handle();
}

bool MockRenderProcessHost::Send(IPC::Message* msg) {
  // Save the message in the sink.
  sink_.OnMessageReceived(*msg);
  delete msg;
  return true;
}

TransportDIB* MockRenderProcessHost::MapTransportDIB(TransportDIB::Id dib_id) {
#if defined(OS_WIN)
  HANDLE duped;
  DuplicateHandle(GetCurrentProcess(), dib_id.handle, GetCurrentProcess(),
                  &duped, 0, TRUE, DUPLICATE_SAME_ACCESS);
  return TransportDIB::Map(duped);
#elif defined(TOOLKIT_GTK)
  return TransportDIB::Map(dib_id.shmkey);
#elif defined(OS_ANDROID)
  // On Android, Handles and Ids are the same underlying type.
  return TransportDIB::Map(dib_id);
#else
  // On POSIX, TransportDIBs are always created in the browser, so we cannot map
  // one from a dib_id.
  return TransportDIB::Create(100 * 100 * 4, 0);
#endif
}

TransportDIB* MockRenderProcessHost::GetTransportDIB(TransportDIB::Id dib_id) {
  if (transport_dib_)
    return transport_dib_;

  transport_dib_ = MapTransportDIB(dib_id);
  return transport_dib_;
}

int MockRenderProcessHost::GetID() const {
  return id_;
}

bool MockRenderProcessHost::HasConnection() const {
  return true;
}

void MockRenderProcessHost::SetIgnoreInputEvents(bool ignore_input_events) {
}

bool MockRenderProcessHost::IgnoreInputEvents() const {
  return false;
}

void MockRenderProcessHost::Cleanup() {
  if (listeners_.IsEmpty()) {
    FOR_EACH_OBSERVER(RenderProcessHostObserver,
                      observers_,
                      RenderProcessHostDestroyed(this));
    base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
    RenderProcessHostImpl::UnregisterHost(GetID());
    deletion_callback_called_ = true;
  }
}

void MockRenderProcessHost::AddPendingView() {
}

void MockRenderProcessHost::RemovePendingView() {
}

void MockRenderProcessHost::SetSuddenTerminationAllowed(bool allowed) {
}

bool MockRenderProcessHost::SuddenTerminationAllowed() const {
  return true;
}

BrowserContext* MockRenderProcessHost::GetBrowserContext() const {
  return browser_context_;
}

bool MockRenderProcessHost::InSameStoragePartition(
    StoragePartition* partition) const {
  // Mock RPHs only have one partition.
  return true;
}

IPC::ChannelProxy* MockRenderProcessHost::GetChannel() {
  return NULL;
}

void MockRenderProcessHost::AddFilter(BrowserMessageFilter* filter) {
}

int MockRenderProcessHost::GetActiveViewCount() {
  int num_active_views = 0;
  scoped_ptr<RenderWidgetHostIterator> widgets(
      RenderWidgetHost::GetRenderWidgetHosts());
  while (RenderWidgetHost* widget = widgets->GetNextHost()) {
    // Count only RenderWidgetHosts in this process.
    if (widget->GetProcess()->GetID() == GetID())
      num_active_views++;
  }
  return num_active_views;
}

bool MockRenderProcessHost::FastShutdownForPageCount(size_t count) {
  if (static_cast<size_t>(GetActiveViewCount()) == count)
    return FastShutdownIfPossible();
  return false;
}

base::TimeDelta MockRenderProcessHost::GetChildProcessIdleTime() const {
  return base::TimeDelta::FromMilliseconds(0);
}

void MockRenderProcessHost::SurfaceUpdated(int32 surface_id) {
}

void MockRenderProcessHost::ResumeRequestsForView(int route_id) {
}

void MockRenderProcessHost::FilterURL(bool empty_allowed, GURL* url) {
  RenderProcessHostImpl::FilterURL(this, empty_allowed, url);
}

#if defined(ENABLE_WEBRTC)
void MockRenderProcessHost::EnableAecDump(const base::FilePath& file) {
}

void MockRenderProcessHost::DisableAecDump() {
}
#endif

bool MockRenderProcessHost::OnMessageReceived(const IPC::Message& msg) {
  IPC::Listener* listener = listeners_.Lookup(msg.routing_id());
  if (listener)
    return listener->OnMessageReceived(msg);
  return false;
}

void MockRenderProcessHost::OnChannelConnected(int32 peer_pid) {
}

MockRenderProcessHostFactory::MockRenderProcessHostFactory() {}

MockRenderProcessHostFactory::~MockRenderProcessHostFactory() {
  // Detach this object from MockRenderProcesses to prevent STLDeleteElements()
  // from calling MockRenderProcessHostFactory::Remove().
  for (ScopedVector<MockRenderProcessHost>::iterator it = processes_.begin();
       it != processes_.end(); ++it) {
    (*it)->SetFactory(NULL);
  }
}

RenderProcessHost* MockRenderProcessHostFactory::CreateRenderProcessHost(
    BrowserContext* browser_context,
    SiteInstance* site_instance) const {
  MockRenderProcessHost* host = new MockRenderProcessHost(browser_context);
  if (host) {
    processes_.push_back(host);
    host->SetFactory(this);
  }
  return host;
}

void MockRenderProcessHostFactory::Remove(MockRenderProcessHost* host) const {
  for (ScopedVector<MockRenderProcessHost>::iterator it = processes_.begin();
       it != processes_.end(); ++it) {
    if (*it == host) {
      processes_.weak_erase(it);
      break;
    }
  }
}

}  // content
<|endoftext|>


<commit_before>#include "QuadKey.hpp"
#include "builders/BuilderContext.hpp"
#include "builders/terrain/TerraBuilder.hpp"
#include "entities/Node.hpp"
#include "entities/Way.hpp"
#include "entities/Area.hpp"
#include "entities/Relation.hpp"
#include "heightmap/FlatElevationProvider.hpp"

#include <boost/test/unit_test.hpp>

#include "test_utils/ElementUtils.hpp"
#include "test_utils/MapCssUtils.hpp"

using namespace utymap;
using namespace utymap::builders;
using namespace utymap::entities;
using namespace utymap::heightmap;
using namespace utymap::index;
using namespace utymap::mapcss;
using namespace utymap::meshing;

const char* StyleSheetString =
"canvas|z1 { grid-cell-size: 1%; layer-priority: water; ele-noise-freq: 0.05; color-noise-freq: 0.1; color:gradient(red); max-area: 5%;"
            "water-ele-noise-freq: 0.05; water-color-noise-freq: 0.1; water-color:gradient(red);  water-max-area: 5%;}"
"area|z1[natural=water] { builders:terrain; terrain-layer:water; }";

struct Builders_Terrain_TerraBuilderFixture
{
    Builders_Terrain_TerraBuilderFixture() :
        stringTablePtr(new StringTable("")),
        styleProviderPtr(MapCssUtils::createStyleProviderFromString(*stringTablePtr, StyleSheetString)),
        eleProvider(),
        builderPtr(nullptr)
    {
    }

    ~Builders_Terrain_TerraBuilderFixture()
    {
        delete builderPtr;
        delete styleProviderPtr;
        delete stringTablePtr;

        std::remove("string.idx");
        std::remove("string.dat");
    }

    FlatElevationProvider eleProvider;
    StringTable* stringTablePtr;
    StyleProvider* styleProviderPtr;
    TerraBuilder* builderPtr;
};

BOOST_FIXTURE_TEST_SUITE(Builders_Terrain_TerraBuilder, Builders_Terrain_TerraBuilderFixture)

BOOST_AUTO_TEST_CASE(GivenLargeWater_WhenComplete_ThenMeshIsNotEmpty)
{
    bool isCalled = false;
    BuilderContext context(QuadKey{ 1, 0, 0 }, *styleProviderPtr, *stringTablePtr, eleProvider,
        [&](const Mesh& mesh) {
            isCalled = true;
            BOOST_CHECK_GT(mesh.vertices.size(), 0);
            BOOST_CHECK_GT(mesh.triangles.size(), 0);
    }, nullptr);
    builderPtr = new TerraBuilder(context);
    ElementUtils::createElement<Area>(*stringTablePtr,
        { { "natural", "water" } },
        { { 0, 0 }, { 20, 0 }, { 20, 20 }, { 0, 20 } }).accept(*builderPtr);

    builderPtr->complete();

    BOOST_CHECK(isCalled);
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>core: fix compilation issue<commit_after>#include "QuadKey.hpp"
#include "builders/BuilderContext.hpp"
#include "builders/terrain/TerraBuilder.hpp"
#include "entities/Node.hpp"
#include "entities/Way.hpp"
#include "entities/Area.hpp"
#include "entities/Relation.hpp"
#include "heightmap/FlatElevationProvider.hpp"

#include <boost/test/unit_test.hpp>

#include "test_utils/ElementUtils.hpp"
#include "test_utils/MapCssUtils.hpp"

using namespace utymap;
using namespace utymap::builders;
using namespace utymap::entities;
using namespace utymap::heightmap;
using namespace utymap::index;
using namespace utymap::mapcss;
using namespace utymap::meshing;

const char* StyleSheetString =
"canvas|z1 { grid-cell-size: 1%; layer-priority: water; ele-noise-freq: 0.05; color-noise-freq: 0.1; color:gradient(red); max-area: 5%;"
            "water-ele-noise-freq: 0.05; water-color-noise-freq: 0.1; water-color:gradient(red);  water-max-area: 5%;}"
"area|z1[natural=water] { builders:terrain; terrain-layer:water; }";

struct Builders_Terrain_TerraBuilderFixture
{
    Builders_Terrain_TerraBuilderFixture() :
        stringTablePtr(new StringTable("")),
        styleProviderPtr(MapCssUtils::createStyleProviderFromString(*stringTablePtr, StyleSheetString)),
        eleProvider(),
        builderPtr(nullptr)
    {
    }

    ~Builders_Terrain_TerraBuilderFixture()
    {
        delete builderPtr;
        delete styleProviderPtr;
        delete stringTablePtr;

        std::remove("string.idx");
        std::remove("string.dat");
    }

    FlatElevationProvider eleProvider;
    StringTable* stringTablePtr;
    StyleProvider* styleProviderPtr;
    TerraBuilder* builderPtr;
};

BOOST_FIXTURE_TEST_SUITE(Builders_Terrain_TerraBuilder, Builders_Terrain_TerraBuilderFixture)

BOOST_AUTO_TEST_CASE(GivenLargeWater_WhenComplete_ThenMeshIsNotEmpty)
{
    bool isCalled = false;
    QuadKey quadKey = {1, 0, 0};
    BuilderContext context(quadKey, *styleProviderPtr, *stringTablePtr, eleProvider,
        [&](const Mesh& mesh) {
            isCalled = true;
            BOOST_CHECK_GT(mesh.vertices.size(), 0);
            BOOST_CHECK_GT(mesh.triangles.size(), 0);
    }, nullptr);
    builderPtr = new TerraBuilder(context);
    ElementUtils::createElement<Area>(*stringTablePtr,
        { { "natural", "water" } },
        { { 0, 0 }, { 20, 0 }, { 20, 20 }, { 0, 20 } }).accept(*builderPtr);

    builderPtr->complete();

    BOOST_CHECK(isCalled);
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>// ヘッダファイルのインクルード
#include <iostream> // C++標準入出力
#include <fstream> // C++ファイル入出力

// main関数の定義
int main(){

  // 変数・配列・オブジェクトの宣言
  std::ifstream fin; // ファイル入力ストリームifstreamのオブジェクトfin.
  char name[32]; // ファイルから読み込んだ名前を格納するchar型配列name.
  int age; // ファイルから読み込んだ年齢を格納するint型変数age.
  char address[128]; // ファイルから読み込んだ住所を格納するchar型配列address.

  // ファイルを開く.
  fin.open("test.txt"); // openで"test.txt"を開く.
  if (!fin){ // openに失敗すると, finはfalseを返す.

    // エラー処理
    std::cout << "Can't open file!" << std::endl; // ファイルが開けない場合のエラーメッセージ.
    return -1; // 異常終了

  }

  // ファイルを読み込む.
  fin >> name >> age >> address; // 入力演算子で"test.txt"から読み込んだ内容をname, age, addressにそれぞれ格納.

  // 読み込んだ内容を出力.
  std::cout << "name: " << name << std::endl; // nameの内容を出力.
  std::cout << "age: " << age << std::endl; // ageの内容を出力.
  std::cout << "address: " << address << std::endl; // addressの内容を出力.

  // ファイルを閉じる.
  fin.close(); // closeで"test.txt"で閉じる.

  // プログラムの終了
  return 0; // 正常終了

}
<commit_msg>fixed ifstream.cpp's comment<commit_after>// ヘッダファイルのインクルード
#include <iostream> // C++標準入出力
#include <fstream> // C++ファイル入出力

// main関数の定義
int main(){

  // 変数・配列・オブジェクトの宣言
  std::ifstream fin; // ファイル入力ストリームifstreamのオブジェクトfin.
  char name[32]; // ファイルから読み込んだ名前を格納するchar型配列name.
  int age; // ファイルから読み込んだ年齢を格納するint型変数age.
  char address[128]; // ファイルから読み込んだ住所を格納するchar型配列address.

  // ファイルを開く.
  fin.open("test.txt"); // openで"test.txt"を開く.
  if (!fin){ // openに失敗すると, finはfalseを返す.

    // エラー処理
    std::cout << "Can't open file!" << std::endl; // ファイルが開けない場合のエラーメッセージ.
    return -1; // 異常終了

  }

  // ファイルを読み込む.
  fin >> name >> age >> address; // 入力演算子で"test.txt"から読み込んだ内容をname, age, addressにそれぞれ格納.

  // 読み込んだ内容を出力.
  std::cout << "name: " << name << std::endl; // nameの内容を出力.
  std::cout << "age: " << age << std::endl; // ageの内容を出力.
  std::cout << "address: " << address << std::endl; // addressの内容を出力.

  // ファイルを閉じる.
  fin.close(); // closeで"test.txt"を閉じる.

  // プログラムの終了
  return 0; // 正常終了

}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2008 Digital Bazaar, Inc.  All rights reserved.
 */
#include "db/crypto/BlockCipherInputStream.h"

using namespace db::crypto;
using namespace db::io;

BlockCipherInputStream::BlockCipherInputStream(
   BlockCipher* cipher, bool cleanupCipher,
   InputStream* os, bool cleanupStream) :
   FilterInputStream(os, cleanupStream),
   mReadBuffer(2048)
{
   mCipher = cipher;
   mCleanupCipher = cleanupCipher;
   mCipherFinished = false;
}

BlockCipherInputStream::~BlockCipherInputStream()
{
   if(mCleanupCipher && mCipher != NULL)
   {
      delete mCipher;
   }
}

int BlockCipherInputStream::read(char* b, int length)
{
   int rval;

   // read from buffer if not empty
   if(!mReadBuffer.isEmpty())
   {
      rval = mReadBuffer.get(b, length);
   }
   else if(mCipherFinished)
   {
      // finished ciphering
      rval = 0;
   }
   else
   {
      // read from underlying stream
      rval = FilterInputStream::read(b, length);

      // cipher data if appropriate
      if(rval >= 0 && mCipher != NULL)
      {
         // update or finish cipher based on data left in underlying stream
         bool success;
         if(rval > 0)
         {
            // update cipher
            success = mCipher->update(b, rval, &mReadBuffer, true);
         }
         else
         {
            // finish cipher
            success = mCipher->finish(&mReadBuffer, true);
            mCipherFinished = true;
         }

         if(success)
         {
            // read from buffer
            rval = mReadBuffer.get(b, length);
         }
         else
         {
            // exception occurred
            rval = -1;
         }
      }
   }

   return rval;
}

void BlockCipherInputStream::setCipher(BlockCipher* cipher, bool cleanup)
{
   if(mCleanupCipher && mCipher != NULL)
   {
      delete mCipher;
   }

   mCipher = cipher;
   mCleanupCipher = cleanup;
   mCipherFinished = false;
}

BlockCipher* BlockCipherInputStream::getCipher()
{
   return mCipher;
}
<commit_msg>Fixed bugs in BlockCipherInputStream.<commit_after>/*
 * Copyright (c) 2008 Digital Bazaar, Inc.  All rights reserved.
 */
#include "db/crypto/BlockCipherInputStream.h"

using namespace db::crypto;
using namespace db::io;

BlockCipherInputStream::BlockCipherInputStream(
   BlockCipher* cipher, bool cleanupCipher,
   InputStream* os, bool cleanupStream) :
   FilterInputStream(os, cleanupStream),
   mReadBuffer(2048)
{
   mCipher = cipher;
   mCleanupCipher = cleanupCipher;
   mCipherFinished = false;
}

BlockCipherInputStream::~BlockCipherInputStream()
{
   if(mCleanupCipher && mCipher != NULL)
   {
      delete mCipher;
   }
}

int BlockCipherInputStream::read(char* b, int length)
{
   int rval = 0;

   // read from buffer if not empty
   if(!mReadBuffer.isEmpty())
   {
      rval = mReadBuffer.get(b, length);
   }
   else if(mCipher == NULL)
   {
      // read from underlying stream, no ciphering
      rval = FilterInputStream::read(b, length);
   }
   else
   {
      // while no data and cipher not finished, read and cipher data
      bool success;
      while(rval == 0 && !mCipherFinished)
      {
         // read from underlying stream
         rval = FilterInputStream::read(b, length);
         if(rval >= 0)
         {
            // update or finish cipher based on data left in underlying stream
            if(rval > 0)
            {
               // update cipher
               success = mCipher->update(b, rval, &mReadBuffer, true);
            }
            else
            {
               // finish cipher
               success = mCipher->finish(&mReadBuffer, true);
               mCipherFinished = true;
            }

            if(success)
            {
               // read from buffer
               rval = mReadBuffer.get(b, length);
            }
            else
            {
               // exception occurred
               rval = -1;
            }
         }
      }
   }

   return rval;
}

void BlockCipherInputStream::setCipher(BlockCipher* cipher, bool cleanup)
{
   if(mCleanupCipher && mCipher != NULL)
   {
      delete mCipher;
   }

   mCipher = cipher;
   mCleanupCipher = cleanup;
   mCipherFinished = false;
}

BlockCipher* BlockCipherInputStream::getCipher()
{
   return mCipher;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <memory>
#include <vector>
#include <boost/python.hpp>

#include <numpy/ndarrayobject.h> // ensure you include this header
#include "boost/numpy.hpp"
#include "IterativeLevel0.hpp"
#include <string>

namespace p = boost::python;
namespace bn = boost::numpy;
using namespace gloc;

typedef Mat<double> MatDouble;

PyObject* add(PyObject* a_, PyObject* b_){
  /*
    various checks
  */
  PyArrayObject* a=(PyArrayObject*) a_;
  PyArrayObject* b=(PyArrayObject*) b_;
  int n = a->dimensions[0];
  int dims[1];
  dims[0] = n;
  PyArrayObject* ret;
  ret = (PyArrayObject*) PyArray_FromDims(1, dims, NPY_DOUBLE);
  int i;
  char *aj=a->data;
  char *bj=b->data;
  double *retj = (double *)ret->data;
  for (i=0; i < n; i++) {
    *retj++ = *((double *)aj) + *((double *)bj);
    aj += a->strides[0];
    bj += b->strides[0];
  }
  return (PyObject *)ret;
}

p::object stdVecToNumpyArray( std::vector<double> const& vec )
{
      npy_intp size = vec.size();

     /* const_cast is rather horrible but we need a writable pointer
        in C++11, vec.data() will do the trick
        but you will still need to const_cast
      */

      double * data = size ? const_cast<double *>(&vec[0])
        : static_cast<double *>(NULL);

    // create a PyObject * from pointer and data
      PyObject * pyObj = PyArray_SimpleNewFromData( 1, &size, NPY_DOUBLE, data );
      boost::python::handle<> handle( pyObj );
      boost::python::numeric::array arr( handle );

    /* The problem of returning arr is twofold: firstly the user can modify
      the data which will betray the const-correctness
      Secondly the lifetime of the data is managed by the C++ API and not the
      lifetime of the numpy array whatsoever. But we have a simple solution..
     */

       return arr.copy(); // copy the object. numpy owns the copy now.
  }

p::object create_vector(npy_intp size){
  double* data = new double[size];

  // create a PyObject * from pointer and data
  PyObject * pyObj = PyArray_SimpleNewFromData( 1, &size, NPY_DOUBLE, data );
  boost::python::handle<> handle( pyObj );
  boost::python::numeric::array arr( handle );

  /* The problem of returning arr is twofold: firstly the user can modify
     the data which will betray the const-correctness
     Secondly the lifetime of the data is managed by the C++ API and not the
     lifetime of the numpy array whatsoever. But we have a simple solution..
  */

  return arr.copy(); // copy the object. numpy owns the copy now.

}

bn::ndarray mywrapper(const std::vector<double>& v) {
  //std::vector<double> v = myfunc();
  Py_intptr_t shape[1] = { static_cast<Py_intptr_t> (v.size()) };
  bn::ndarray result = bn::zeros(1, shape, bn::dtype::get_builtin<double>());
  std::copy(v.begin(), v.end(), reinterpret_cast<double*>(result.get_data()));
  return result;

}

struct World
{
  World(const std::string& msg): msg(msg) {} // added constructor
  void set(std::string msg) { this->msg = msg; }
  std::string greet() { return msg; }
  std::string msg;
};

static bn::ndarray next_from_stream(p::object & self){
  auto frame = p::extract<StreamReader*>(self)()->get_next();
  if(frame == nullptr){
    return bn::from_object(self);
  }

  return mywrapper(frame->get_data());
}

static bn::ndarray py_get_next(p::object self){
  auto frame = p::extract<std::shared_ptr<MatDouble> >(self)();
  //auto frame = read.get_next();

  if(frame == nullptr){
    return bn::from_object(self);
  }

  return bn::from_data(
      frame->get_raw_data(),
      bn::dtype::get_builtin<double>(),
      p::make_tuple(frame->height(), frame->width()),
      p::make_tuple(frame->width() * sizeof(double), sizeof(double)),
      self
                       );
}

struct SpTest{
  double *data;
  SpTest(){
    data = new double[100000000];
  }
  ~SpTest(){
    if(data){
      delete[] data;
    }
  }
  static std::shared_ptr<SpTest> create(){return std::shared_ptr<SpTest>(new SpTest);}
  std::string hello() { return "just nod if you can hear me 2";}
};

char const* test_function(){
  return "hello world";
}

std::vector<double> myfunc(){
  std::vector<double> v(100000, 1.);
  return v;
}

BOOST_PYTHON_MODULE(gloripex){

  bn::initialize();
  Py_Initialize();
  import_array();
  p::def("test_function", test_function );

  p::def("create_vector", create_vector);

  p::def("add2", add);
  p::class_<MatDouble, std::shared_ptr<MatDouble> >("MatDouble", p::init<>())
      .def("get_size", &MatDouble::get_size)
      .def("to_array", &py_get_next)
      ;

  p::class_<World>("World", p::init<std::string>())
      .def("greet", &World::greet)
      .def("set", &World::set)
      ;

  p::class_<StreamReader>("StreamReader", p::init<std::string>())
<<<<<<< HEAD
      .def("get_next", &StreamReader::get_next)
      .def("next", &next_from_stream);

  // shared pointer test for ownertest
  p::class_<SpTest, std::shared_ptr<SpTest> >("SpTest", p::init<>())
      .def("create", &SpTest::create)
      .staticmethod("create")
      .def("hello", &SpTest::hello)
      ;
=======
      .def("get_next", &py_get_next);//, p::return_value_policy<p::manage_new_object>());
>>>>>>> 7fd4ae129676fbb219e37f64210575b5088a7511
}
<commit_msg>numpy api 1.7 ++<commit_after>#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <iostream>
#include <memory>
#include <vector>
#include <boost/python.hpp>

#include <numpy/ndarrayobject.h> // ensure you include this header
#include "boost/numpy.hpp"
#include "IterativeLevel0.hpp"
#include <string>

namespace p = boost::python;
namespace bn = boost::numpy;
using namespace gloc;

typedef Mat<double> MatDouble;

PyObject* add(PyObject* a_, PyObject* b_){
  /*
    various checks
  */
  PyArrayObject* a=(PyArrayObject*) a_;
  PyArrayObject* b=(PyArrayObject*) b_;

  int n = PyArray_NDIM(a);
  int dims[1];
  dims[0] = n;
  PyArrayObject* ret;
  ret = (PyArrayObject*) PyArray_FromDims(1, dims, NPY_DOUBLE);
  int i;
  char *aj= reinterpret_cast<char*>(PyArray_DATA(a));
  char *bj= reinterpret_cast<char*>(PyArray_DATA(b));
  double *retj = (double *)PyArray_DATA(ret);
  for (i=0; i < n; i++) {
    *retj++ = *((double *)aj) + *((double *)bj);
    aj += PyArray_STRIDES(a)[0];
    bj += PyArray_STRIDES(b)[0];
  }
  return (PyObject *)ret;
}

bn::ndarray mywrapper(const std::vector<double>& v) {
  //std::vector<double> v = myfunc();
  Py_intptr_t shape[1] = { static_cast<Py_intptr_t> (v.size()) };
  bn::ndarray result = bn::zeros(1, shape, bn::dtype::get_builtin<double>());
  std::copy(v.begin(), v.end(), reinterpret_cast<double*>(result.get_data()));
  return result;

}

struct World
{
  World(const std::string& msg): msg(msg) {} // added constructor
  void set(std::string msg) { this->msg = msg; }
  std::string greet() { return msg; }
  std::string msg;
};

static bn::ndarray next_from_stream(p::object & self){
  auto frame = p::extract<StreamReader*>(self)()->get_next();
  if(frame == nullptr){
    return bn::from_object(self);
  }

  return mywrapper(frame->get_data());
}

static bn::ndarray py_get_next(p::object self){
  auto frame = p::extract<std::shared_ptr<MatDouble> >(self)();
  //auto frame = read.get_next();

  if(frame == nullptr){
    return bn::from_object(self);
  }

  return bn::from_data(
      frame->get_raw_data(),
      bn::dtype::get_builtin<double>(),
      p::make_tuple(frame->height(), frame->width()),
      p::make_tuple(frame->width() * sizeof(double), sizeof(double)),
      self
                       );
}

struct SpTest{
  double *data;
  SpTest(){
    data = new double[100000000];
  }
  ~SpTest(){
    if(data){
      delete[] data;
    }
  }
  static std::shared_ptr<SpTest> create(){return std::shared_ptr<SpTest>(new SpTest);}
  std::string hello() { return "just nod if you can hear me 2";}
};

char const* test_function(){
  return "hello world";
}

std::vector<double> myfunc(){
  std::vector<double> v(100000, 1.);
  return v;
}

BOOST_PYTHON_MODULE(gloripex){

  bn::initialize();
  Py_Initialize();
  import_array();
  p::def("test_function", test_function );

  p::def("add2", add);
  p::class_<MatDouble, std::shared_ptr<MatDouble> >("MatDouble", p::init<>())
      .def("get_size", &MatDouble::get_size)
      .def("to_array", &py_get_next)
      ;

  p::class_<World>("World", p::init<std::string>())
      .def("greet", &World::greet)
      .def("set", &World::set)
      ;

  p::class_<StreamReader>("StreamReader", p::init<std::string>())
      .def("get_next", &StreamReader::get_next)
      .def("next", &next_from_stream);

  // shared pointer test for ownertest
  p::class_<SpTest, std::shared_ptr<SpTest> >("SpTest", p::init<>())
      .def("create", &SpTest::create)
      .staticmethod("create")
      .def("hello", &SpTest::hello)
      ;

}
<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2006 Torus Knot Software Ltd
Also see acknowledgements in Readme.html

This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.

This program 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 program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.

You may alternatively use this source under the terms of a specific version of
the OGRE Unrestricted License provided you have obtained such a license from
Torus Knot Software Ltd.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"

#include "OgreSerializer.h"
#include "OgreLogManager.h"
#include "OgreDataStream.h"
#include "OgreException.h"
#include "OgreVector3.h"
#include "OgreQuaternion.h"

namespace Ogre {

    /// stream overhead = ID + size
    const size_t STREAM_OVERHEAD_SIZE = sizeof(uint16) + sizeof(uint32);
    const uint16 HEADER_STREAM_ID = 0x1000;
    const uint16 OTHER_ENDIAN_HEADER_STREAM_ID = 0x0010;
    //---------------------------------------------------------------------
    Serializer::Serializer()
    {
        // Version number
        mVersion = "[Serializer_v1.00]";
		mFlipEndian = false;
    }
    //---------------------------------------------------------------------
    Serializer::~Serializer()
    {
    }
    //---------------------------------------------------------------------
	void Serializer::determineEndianness(DataStreamPtr& stream)
	{
		if (stream->tell() != 0)
		{
			OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
				"Can only determine the endianness of the input stream if it "
				"is at the start", "Serializer::determineEndianness");
		}

		uint16 dest;
		// read header id manually (no conversion)
        size_t actually_read = stream->read(&dest, sizeof(uint16));
		// skip back
        stream->skip(0 - actually_read);
        if (actually_read != sizeof(uint16))
        {
            // end of file?
            OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
                        "Couldn't read 16 bit header value from input stream.",
                        "Serializer::determineEndianness");
        }
		if (dest == HEADER_STREAM_ID)
		{
			mFlipEndian = false;
		}
		else if (dest == OTHER_ENDIAN_HEADER_STREAM_ID)
		{
			mFlipEndian = true;
		}
		else
		{
			OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
				"Header chunk didn't match either endian: Corrupted stream?",
				"Serializer::determineEndianness");
		}
	}
    //---------------------------------------------------------------------
	void Serializer::determineEndianness(Endian requestedEndian)
	{
		switch(requestedEndian)
		{
		case ENDIAN_NATIVE:
			mFlipEndian = false;
			break;
		case ENDIAN_BIG:
#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
			mFlipEndian = false;
#else
			mFlipEndian = true;
#endif
			break;
		case ENDIAN_LITTLE:
#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
			mFlipEndian = true;
#else
			mFlipEndian = false;
#endif
			break;
		}
	}
    //---------------------------------------------------------------------
    void Serializer::writeFileHeader(void)
    {

        uint16 val = HEADER_STREAM_ID;
        writeShorts(&val, 1);

        writeString(mVersion);

    }
    //---------------------------------------------------------------------
    void Serializer::writeChunkHeader(uint16 id, size_t size)
    {
        writeShorts(&id, 1);
		uint32 uint32size = static_cast<uint32>(size);
        writeInts(&uint32size, 1);
    }
    //---------------------------------------------------------------------
    void Serializer::writeFloats(const float* const pFloat, size_t count)
    {
		if (mFlipEndian)
		{
            float * pFloatToWrite = (float *)malloc(sizeof(float) * count);
            memcpy(pFloatToWrite, pFloat, sizeof(float) * count);

            flipToLittleEndian(pFloatToWrite, sizeof(float), count);
            writeData(pFloatToWrite, sizeof(float), count);

            free(pFloatToWrite);
		}
		else
		{
            writeData(pFloat, sizeof(float), count);
		}
    }
    //---------------------------------------------------------------------
    void Serializer::writeFloats(const double* const pDouble, size_t count)
    {
		// Convert to float, then write
		float* tmp = new float[count];
		for (unsigned int i = 0; i < count; ++i)
		{
			tmp[i] = static_cast<float>(pDouble[i]);
		}
		if(mFlipEndian)
		{
            flipToLittleEndian(tmp, sizeof(float), count);
            writeData(tmp, sizeof(float), count);
		}
		else
		{
            writeData(tmp, sizeof(float), count);
		}
		delete [] tmp;
    }
    //---------------------------------------------------------------------
    void Serializer::writeShorts(const uint16* const pShort, size_t count = 1)
    {
		if(mFlipEndian)
		{
            unsigned short * pShortToWrite = (unsigned short *)malloc(sizeof(unsigned short) * count);
            memcpy(pShortToWrite, pShort, sizeof(unsigned short) * count);

            flipToLittleEndian(pShortToWrite, sizeof(unsigned short), count);
            writeData(pShortToWrite, sizeof(unsigned short), count);

            free(pShortToWrite);
		}
		else
		{
            writeData(pShort, sizeof(unsigned short), count);
		}
    }
    //---------------------------------------------------------------------
    void Serializer::writeInts(const uint32* const pInt, size_t count = 1)
    {
		if(mFlipEndian)
		{
            unsigned int * pIntToWrite = (unsigned int *)malloc(sizeof(unsigned int) * count);
            memcpy(pIntToWrite, pInt, sizeof(unsigned int) * count);

            flipToLittleEndian(pIntToWrite, sizeof(unsigned int), count);
            writeData(pIntToWrite, sizeof(unsigned int), count);

            free(pIntToWrite);
		}
		else
		{
            writeData(pInt, sizeof(unsigned int), count);
		}
    }
    //---------------------------------------------------------------------
    //---------------------------------------------------------------------
    void Serializer::writeBools(const bool* const pBool, size_t count = 1)
    {
    //no endian flipping for 1-byte bools
    //XXX Nasty Hack to convert to 1-byte bools
#	if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
        char * pCharToWrite = (char *)malloc(sizeof(char) * count);
        for(int i = 0; i < count; i++)
        {
            *(char *)(pCharToWrite + i) = *(bool *)(pBool + i);
        }

        writeData(pCharToWrite, sizeof(char), count);

        free(pCharToWrite);
#	else
        writeData(pBool, sizeof(bool), count);
#	endif

    }

    //---------------------------------------------------------------------
    void Serializer::writeData(const void* const buf, size_t size, size_t count)
    {
        fwrite((void* const)buf, size, count, mpfFile);
    }
    //---------------------------------------------------------------------
    void Serializer::writeString(const String& string)
    {
        fputs(string.c_str(), mpfFile);
        // Write terminating newline char
        fputc('\n', mpfFile);
    }
    //---------------------------------------------------------------------
    void Serializer::readFileHeader(DataStreamPtr& stream)
    {
        unsigned short headerID;

        // Read header ID
        readShorts(stream, &headerID, 1);

        if (headerID == HEADER_STREAM_ID)
        {
            // Read version
            String ver = readString(stream);
            if (ver != mVersion)
            {
                OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,
                    "Invalid file: version incompatible, file reports " + String(ver) +
                    " Serializer is version " + mVersion,
                    "Serializer::readFileHeader");
            }
        }
        else
        {
            OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Invalid file: no header",
                "Serializer::readFileHeader");
        }

    }
    //---------------------------------------------------------------------
    unsigned short Serializer::readChunk(DataStreamPtr& stream)
    {
        unsigned short id;
        readShorts(stream, &id, 1);

        readInts(stream, &mCurrentstreamLen, 1);
        return id;
    }
    //---------------------------------------------------------------------
    void Serializer::readBools(DataStreamPtr& stream, bool* pDest, size_t count)
    {
        //XXX Nasty Hack to convert 1 byte bools to 4 byte bools
#	if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
        char * pTemp = (char *)malloc(1*count); // to hold 1-byte bools
        stream->read(pTemp, 1 * count);
        for(int i = 0; i < count; i++)
            *(bool *)(pDest + i) = *(char *)(pTemp + i);

        free (pTemp);
#	else
        stream->read(pDest, sizeof(bool) * count);
#	endif
        //no flipping on 1-byte datatypes
    }
    //---------------------------------------------------------------------
    void Serializer::readFloats(DataStreamPtr& stream, float* pDest, size_t count)
    {
        stream->read(pDest, sizeof(float) * count);
        flipFromLittleEndian(pDest, sizeof(float), count);
    }
    //---------------------------------------------------------------------
    void Serializer::readFloats(DataStreamPtr& stream, double* pDest, size_t count)
    {
		// Read from float, convert to double
		float* tmp = new float[count];
		float* ptmp = tmp;
        stream->read(tmp, sizeof(float) * count);
        flipFromLittleEndian(tmp, sizeof(float), count);
		// Convert to doubles (no cast required)
		while(count--)
		{
			*pDest++ = *ptmp++;
		}
		delete [] tmp;
    }
    //---------------------------------------------------------------------
    void Serializer::readShorts(DataStreamPtr& stream, unsigned short* pDest, size_t count)
    {
        stream->read(pDest, sizeof(unsigned short) * count);
        flipFromLittleEndian(pDest, sizeof(unsigned short), count);
    }
    //---------------------------------------------------------------------
    void Serializer::readInts(DataStreamPtr& stream, unsigned int* pDest, size_t count)
    {
        stream->read(pDest, sizeof(unsigned int) * count);
        flipFromLittleEndian(pDest, sizeof(unsigned int), count);
    }
    //---------------------------------------------------------------------
    String Serializer::readString(DataStreamPtr& stream, size_t numChars)
    {
        assert (numChars <= 255);
        char str[255];
        stream->read(str, numChars);
        str[numChars] = '\0';
        return str;
    }
    //---------------------------------------------------------------------
    String Serializer::readString(DataStreamPtr& stream)
    {
        return stream->getLine(false);
    }
    //---------------------------------------------------------------------
    void Serializer::writeObject(const Vector3& vec)
    {
        writeFloats(vec.ptr(), 3);
    }
    //---------------------------------------------------------------------
    void Serializer::writeObject(const Quaternion& q)
    {
        float tmp[4] = { q.x, q.y, q.z, q.w };
        writeFloats(tmp, 4);
    }
    //---------------------------------------------------------------------
    void Serializer::readObject(DataStreamPtr& stream, Vector3& pDest)
    {
        readFloats(stream, pDest.ptr(), 3);
    }
    //---------------------------------------------------------------------
    void Serializer::readObject(DataStreamPtr& stream, Quaternion& pDest)
    {
        float tmp[4];
        readFloats(stream, tmp, 4);
        pDest.x = tmp[0];
        pDest.y = tmp[1];
        pDest.z = tmp[2];
        pDest.w = tmp[3];
    }
    //---------------------------------------------------------------------

    void Serializer::flipToLittleEndian(void* pData, size_t size, size_t count)
    {
		if(mFlipEndian)
		{
	        flipEndian(pData, size, count);
		}
    }

    void Serializer::flipFromLittleEndian(void* pData, size_t size, size_t count)
    {
		if(mFlipEndian)
		{
	        flipEndian(pData, size, count);
		}
    }

    void Serializer::flipEndian(void * pData, size_t size, size_t count)
    {
        for(unsigned int index = 0; index < count; index++)
        {
            flipEndian((void *)((long)pData + (index * size)), size);
        }
    }

    void Serializer::flipEndian(void * pData, size_t size)
    {
        char swapByte;
        for(unsigned int byteIndex = 0; byteIndex < size/2; byteIndex++)
        {
            swapByte = *(char *)((long)pData + byteIndex);
            *(char *)((long)pData + byteIndex) = *(char *)((long)pData + size - byteIndex - 1);
            *(char *)((long)pData + size - byteIndex - 1) = swapByte;
        }
    }

}

<commit_msg>Warning fixing<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2006 Torus Knot Software Ltd
Also see acknowledgements in Readme.html

This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.

This program 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 program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.

You may alternatively use this source under the terms of a specific version of
the OGRE Unrestricted License provided you have obtained such a license from
Torus Knot Software Ltd.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"

#include "OgreSerializer.h"
#include "OgreLogManager.h"
#include "OgreDataStream.h"
#include "OgreException.h"
#include "OgreVector3.h"
#include "OgreQuaternion.h"

namespace Ogre {

    /// stream overhead = ID + size
    const size_t STREAM_OVERHEAD_SIZE = sizeof(uint16) + sizeof(uint32);
    const uint16 HEADER_STREAM_ID = 0x1000;
    const uint16 OTHER_ENDIAN_HEADER_STREAM_ID = 0x0010;
    //---------------------------------------------------------------------
    Serializer::Serializer()
    {
        // Version number
        mVersion = "[Serializer_v1.00]";
		mFlipEndian = false;
    }
    //---------------------------------------------------------------------
    Serializer::~Serializer()
    {
    }
    //---------------------------------------------------------------------
	void Serializer::determineEndianness(DataStreamPtr& stream)
	{
		if (stream->tell() != 0)
		{
			OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
				"Can only determine the endianness of the input stream if it "
				"is at the start", "Serializer::determineEndianness");
		}

		uint16 dest;
		// read header id manually (no conversion)
        size_t actually_read = stream->read(&dest, sizeof(uint16));
		// skip back
        stream->skip(0 - (long)actually_read);
        if (actually_read != sizeof(uint16))
        {
            // end of file?
            OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
                        "Couldn't read 16 bit header value from input stream.",
                        "Serializer::determineEndianness");
        }
		if (dest == HEADER_STREAM_ID)
		{
			mFlipEndian = false;
		}
		else if (dest == OTHER_ENDIAN_HEADER_STREAM_ID)
		{
			mFlipEndian = true;
		}
		else
		{
			OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
				"Header chunk didn't match either endian: Corrupted stream?",
				"Serializer::determineEndianness");
		}
	}
    //---------------------------------------------------------------------
	void Serializer::determineEndianness(Endian requestedEndian)
	{
		switch(requestedEndian)
		{
		case ENDIAN_NATIVE:
			mFlipEndian = false;
			break;
		case ENDIAN_BIG:
#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
			mFlipEndian = false;
#else
			mFlipEndian = true;
#endif
			break;
		case ENDIAN_LITTLE:
#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
			mFlipEndian = true;
#else
			mFlipEndian = false;
#endif
			break;
		}
	}
    //---------------------------------------------------------------------
    void Serializer::writeFileHeader(void)
    {

        uint16 val = HEADER_STREAM_ID;
        writeShorts(&val, 1);

        writeString(mVersion);

    }
    //---------------------------------------------------------------------
    void Serializer::writeChunkHeader(uint16 id, size_t size)
    {
        writeShorts(&id, 1);
		uint32 uint32size = static_cast<uint32>(size);
        writeInts(&uint32size, 1);
    }
    //---------------------------------------------------------------------
    void Serializer::writeFloats(const float* const pFloat, size_t count)
    {
		if (mFlipEndian)
		{
            float * pFloatToWrite = (float *)malloc(sizeof(float) * count);
            memcpy(pFloatToWrite, pFloat, sizeof(float) * count);

            flipToLittleEndian(pFloatToWrite, sizeof(float), count);
            writeData(pFloatToWrite, sizeof(float), count);

            free(pFloatToWrite);
		}
		else
		{
            writeData(pFloat, sizeof(float), count);
		}
    }
    //---------------------------------------------------------------------
    void Serializer::writeFloats(const double* const pDouble, size_t count)
    {
		// Convert to float, then write
		float* tmp = new float[count];
		for (unsigned int i = 0; i < count; ++i)
		{
			tmp[i] = static_cast<float>(pDouble[i]);
		}
		if(mFlipEndian)
		{
            flipToLittleEndian(tmp, sizeof(float), count);
            writeData(tmp, sizeof(float), count);
		}
		else
		{
            writeData(tmp, sizeof(float), count);
		}
		delete [] tmp;
    }
    //---------------------------------------------------------------------
    void Serializer::writeShorts(const uint16* const pShort, size_t count = 1)
    {
		if(mFlipEndian)
		{
            unsigned short * pShortToWrite = (unsigned short *)malloc(sizeof(unsigned short) * count);
            memcpy(pShortToWrite, pShort, sizeof(unsigned short) * count);

            flipToLittleEndian(pShortToWrite, sizeof(unsigned short), count);
            writeData(pShortToWrite, sizeof(unsigned short), count);

            free(pShortToWrite);
		}
		else
		{
            writeData(pShort, sizeof(unsigned short), count);
		}
    }
    //---------------------------------------------------------------------
    void Serializer::writeInts(const uint32* const pInt, size_t count = 1)
    {
		if(mFlipEndian)
		{
            unsigned int * pIntToWrite = (unsigned int *)malloc(sizeof(unsigned int) * count);
            memcpy(pIntToWrite, pInt, sizeof(unsigned int) * count);

            flipToLittleEndian(pIntToWrite, sizeof(unsigned int), count);
            writeData(pIntToWrite, sizeof(unsigned int), count);

            free(pIntToWrite);
		}
		else
		{
            writeData(pInt, sizeof(unsigned int), count);
		}
    }
    //---------------------------------------------------------------------
    //---------------------------------------------------------------------
    void Serializer::writeBools(const bool* const pBool, size_t count = 1)
    {
    //no endian flipping for 1-byte bools
    //XXX Nasty Hack to convert to 1-byte bools
#	if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
        char * pCharToWrite = (char *)malloc(sizeof(char) * count);
        for(int i = 0; i < count; i++)
        {
            *(char *)(pCharToWrite + i) = *(bool *)(pBool + i);
        }

        writeData(pCharToWrite, sizeof(char), count);

        free(pCharToWrite);
#	else
        writeData(pBool, sizeof(bool), count);
#	endif

    }

    //---------------------------------------------------------------------
    void Serializer::writeData(const void* const buf, size_t size, size_t count)
    {
        fwrite((void* const)buf, size, count, mpfFile);
    }
    //---------------------------------------------------------------------
    void Serializer::writeString(const String& string)
    {
        fputs(string.c_str(), mpfFile);
        // Write terminating newline char
        fputc('\n', mpfFile);
    }
    //---------------------------------------------------------------------
    void Serializer::readFileHeader(DataStreamPtr& stream)
    {
        unsigned short headerID;

        // Read header ID
        readShorts(stream, &headerID, 1);

        if (headerID == HEADER_STREAM_ID)
        {
            // Read version
            String ver = readString(stream);
            if (ver != mVersion)
            {
                OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,
                    "Invalid file: version incompatible, file reports " + String(ver) +
                    " Serializer is version " + mVersion,
                    "Serializer::readFileHeader");
            }
        }
        else
        {
            OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Invalid file: no header",
                "Serializer::readFileHeader");
        }

    }
    //---------------------------------------------------------------------
    unsigned short Serializer::readChunk(DataStreamPtr& stream)
    {
        unsigned short id;
        readShorts(stream, &id, 1);

        readInts(stream, &mCurrentstreamLen, 1);
        return id;
    }
    //---------------------------------------------------------------------
    void Serializer::readBools(DataStreamPtr& stream, bool* pDest, size_t count)
    {
        //XXX Nasty Hack to convert 1 byte bools to 4 byte bools
#	if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
        char * pTemp = (char *)malloc(1*count); // to hold 1-byte bools
        stream->read(pTemp, 1 * count);
        for(int i = 0; i < count; i++)
            *(bool *)(pDest + i) = *(char *)(pTemp + i);

        free (pTemp);
#	else
        stream->read(pDest, sizeof(bool) * count);
#	endif
        //no flipping on 1-byte datatypes
    }
    //---------------------------------------------------------------------
    void Serializer::readFloats(DataStreamPtr& stream, float* pDest, size_t count)
    {
        stream->read(pDest, sizeof(float) * count);
        flipFromLittleEndian(pDest, sizeof(float), count);
    }
    //---------------------------------------------------------------------
    void Serializer::readFloats(DataStreamPtr& stream, double* pDest, size_t count)
    {
		// Read from float, convert to double
		float* tmp = new float[count];
		float* ptmp = tmp;
        stream->read(tmp, sizeof(float) * count);
        flipFromLittleEndian(tmp, sizeof(float), count);
		// Convert to doubles (no cast required)
		while(count--)
		{
			*pDest++ = *ptmp++;
		}
		delete [] tmp;
    }
    //---------------------------------------------------------------------
    void Serializer::readShorts(DataStreamPtr& stream, unsigned short* pDest, size_t count)
    {
        stream->read(pDest, sizeof(unsigned short) * count);
        flipFromLittleEndian(pDest, sizeof(unsigned short), count);
    }
    //---------------------------------------------------------------------
    void Serializer::readInts(DataStreamPtr& stream, unsigned int* pDest, size_t count)
    {
        stream->read(pDest, sizeof(unsigned int) * count);
        flipFromLittleEndian(pDest, sizeof(unsigned int), count);
    }
    //---------------------------------------------------------------------
    String Serializer::readString(DataStreamPtr& stream, size_t numChars)
    {
        assert (numChars <= 255);
        char str[255];
        stream->read(str, numChars);
        str[numChars] = '\0';
        return str;
    }
    //---------------------------------------------------------------------
    String Serializer::readString(DataStreamPtr& stream)
    {
        return stream->getLine(false);
    }
    //---------------------------------------------------------------------
    void Serializer::writeObject(const Vector3& vec)
    {
        writeFloats(vec.ptr(), 3);
    }
    //---------------------------------------------------------------------
    void Serializer::writeObject(const Quaternion& q)
    {
        float tmp[4] = { q.x, q.y, q.z, q.w };
        writeFloats(tmp, 4);
    }
    //---------------------------------------------------------------------
    void Serializer::readObject(DataStreamPtr& stream, Vector3& pDest)
    {
        readFloats(stream, pDest.ptr(), 3);
    }
    //---------------------------------------------------------------------
    void Serializer::readObject(DataStreamPtr& stream, Quaternion& pDest)
    {
        float tmp[4];
        readFloats(stream, tmp, 4);
        pDest.x = tmp[0];
        pDest.y = tmp[1];
        pDest.z = tmp[2];
        pDest.w = tmp[3];
    }
    //---------------------------------------------------------------------

    void Serializer::flipToLittleEndian(void* pData, size_t size, size_t count)
    {
		if(mFlipEndian)
		{
	        flipEndian(pData, size, count);
		}
    }

    void Serializer::flipFromLittleEndian(void* pData, size_t size, size_t count)
    {
		if(mFlipEndian)
		{
	        flipEndian(pData, size, count);
		}
    }

    void Serializer::flipEndian(void * pData, size_t size, size_t count)
    {
        for(unsigned int index = 0; index < count; index++)
        {
            flipEndian((void *)((long)pData + (index * size)), size);
        }
    }

    void Serializer::flipEndian(void * pData, size_t size)
    {
        char swapByte;
        for(unsigned int byteIndex = 0; byteIndex < size/2; byteIndex++)
        {
            swapByte = *(char *)((long)pData + byteIndex);
            *(char *)((long)pData + byteIndex) = *(char *)((long)pData + size - byteIndex - 1);
            *(char *)((long)pData + size - byteIndex - 1) = swapByte;
        }
    }

}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: objectanimator.cxx,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.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#include <svx/sdr/animation/objectanimator.hxx>
#include <tools/debug.hxx>
#include <svx/sdr/animation/animationstate.hxx>

// for SOLARIS compiler include of algorithm part of _STL is necesary to
// get access to basic algos like ::std::find
#include <algorithm>

//////////////////////////////////////////////////////////////////////////////

namespace sdr
{
    namespace animation
    {
        ObjectAnimator::ObjectAnimator()
        {
        }

        ObjectAnimator::~ObjectAnimator()
        {
        }

        // get the list count
        sal_uInt32 ObjectAnimator::Count() const
        {
            return maAnimationStates.size();
        }

        // Remove AnimationState member
        void ObjectAnimator::RemoveAnimationState(AnimationState& rAnimationState)
        {
            const AnimationStateVector::iterator aFindResult = ::std::find(
                maAnimationStates.begin(), maAnimationStates.end(), &rAnimationState);

            if(aFindResult != maAnimationStates.end())
            {
                // #114376# remember content for next call
                AnimationState* pErasedState = *aFindResult;
                maAnimationStates.erase(aFindResult);
                RemoveEvent(pErasedState);
            }
        }

        // Add AnimationState member
        void ObjectAnimator::AddAnimationState(AnimationState& rAnimationState)
        {
            maAnimationStates.push_back(&rAnimationState);
            InsertEvent(&rAnimationState);
        }
    } // end of namespace animation
} // end of namespace sdr

//////////////////////////////////////////////////////////////////////////////
// eof
<commit_msg>INTEGRATION: CWS aw033 (1.4.16); FILE MERGED 2008/05/14 13:59:49 aw 1.4.16.4: RESYNC: (1.5-1.6); FILE MERGED 2008/01/22 12:29:29 aw 1.4.16.3: adaptions and 1st stripping 2006/09/26 19:19:34 aw 1.4.16.2: RESYNC: (1.4-1.5); FILE MERGED 2006/08/09 17:08:56 aw 1.4.16.1: #i39532#<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: objectanimator.cxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#include <svx/sdr/animation/objectanimator.hxx>
#include <tools/debug.hxx>
#include <svx/sdr/animation/animationstate.hxx>

//////////////////////////////////////////////////////////////////////////////

namespace sdr
{
    namespace animation
    {
        primitiveAnimator::primitiveAnimator()
        :   Scheduler()
        {
        }

        primitiveAnimator::~primitiveAnimator()
        {
        }
    } // end of namespace animation
} // end of namespace sdr

//////////////////////////////////////////////////////////////////////////////
// eof
<|endoftext|>


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

#include <folly/experimental/symbolizer/Symbolizer.h>

#include <cstdlib>

#include <folly/Range.h>
#include <folly/String.h>
#include <folly/portability/GTest.h>

namespace folly {
namespace symbolizer {
namespace test {

void foo() {}

TEST(Symbolizer, Single) {
  Symbolizer symbolizer;
  SymbolizedFrame a;
  ASSERT_TRUE(symbolizer.symbolize(reinterpret_cast<uintptr_t>(foo), a));
  EXPECT_EQ("folly::symbolizer::test::foo()", a.demangledName());

  // The version of clang we use doesn't generate a `.debug_aranges` section,
  // which the symbolizer needs to lookup the filename.
  constexpr bool built_with_clang =
#ifdef __clang__
      true;
#else
      false;
#endif
  if (!built_with_clang) {
    auto path = a.location.file.toString();
    folly::StringPiece basename(path);
    auto pos = basename.rfind('/');
    if (pos != folly::StringPiece::npos) {
      basename.advance(pos + 1);
    }
    EXPECT_EQ("SymbolizerTest.cpp", basename.str());
  }
}

FrameArray<100>* framesToFill{nullptr};

int comparator(const void* ap, const void* bp) {
  getStackTrace(*framesToFill);

  int a = *static_cast<const int*>(ap);
  int b = *static_cast<const int*>(bp);
  return a < b ? -1 : a > b ? 1 : 0;
}

// Test stack frames...
FOLLY_NOINLINE void bar();

void bar(FrameArray<100>& frames) {
  framesToFill = &frames;
  int a[2] = {1, 2};
  // Use qsort, which is in a different library
  qsort(a, 2, sizeof(int), comparator);
  framesToFill = nullptr;
}

class ElfCacheTest : public testing::Test {
 protected:
  void SetUp() override;
};

// Capture "golden" stack trace with default-configured Symbolizer
FrameArray<100> goldenFrames;

void ElfCacheTest::SetUp() {
  bar(goldenFrames);
  Symbolizer symbolizer;
  symbolizer.symbolize(goldenFrames);
  // At least 3 stack frames from us + getStackTrace()
  ASSERT_LE(4, goldenFrames.frameCount);
}

void runElfCacheTest(Symbolizer& symbolizer) {
  FrameArray<100> frames = goldenFrames;
  for (size_t i = 0; i < frames.frameCount; ++i) {
    frames.frames[i].clear();
  }
  symbolizer.symbolize(frames);
  ASSERT_LE(4, frames.frameCount);
  for (size_t i = 1; i < 4; ++i) {
    EXPECT_STREQ(goldenFrames.frames[i].name, frames.frames[i].name);
  }
}

TEST_F(ElfCacheTest, TinyElfCache) {
  ElfCache cache(1);
  Symbolizer symbolizer(&cache);
  // Run twice, in case the wrong stuff gets evicted?
  for (size_t i = 0; i < 2; ++i) {
    runElfCacheTest(symbolizer);
  }
}

TEST_F(ElfCacheTest, SignalSafeElfCache) {
  SignalSafeElfCache cache(100);
  Symbolizer symbolizer(&cache);
  for (size_t i = 0; i < 2; ++i) {
    runElfCacheTest(symbolizer);
  }
}

TEST(SymbolizerTest, SymbolCache) {
  Symbolizer symbolizer(nullptr, Dwarf::LocationInfoMode::FULL, 100);

  FrameArray<100> frames;
  bar(frames);
  symbolizer.symbolize(frames);

  FrameArray<100> frames2;
  bar(frames2);
  symbolizer.symbolize(frames2);
  for (size_t i = 0; i < frames.frameCount; i++) {
    EXPECT_STREQ(frames.frames[i].name, frames2.frames[i].name);
  }
}

} // namespace test
} // namespace symbolizer
} // namespace folly

// Can't use initFacebookLight since that would install its own signal handlers
// Can't use initFacebookNoSignals since we cannot depend on common
int main(int argc, char** argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<commit_msg>folly: symbolizer: test: re-enable test on clang as .debug_aranges is produced by the compiler<commit_after>/*
 * Copyright 2013-present Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <folly/experimental/symbolizer/Symbolizer.h>

#include <cstdlib>

#include <folly/Range.h>
#include <folly/String.h>
#include <folly/portability/GTest.h>

namespace folly {
namespace symbolizer {
namespace test {

void foo() {}

TEST(Symbolizer, Single) {
  Symbolizer symbolizer;
  SymbolizedFrame a;
  ASSERT_TRUE(symbolizer.symbolize(reinterpret_cast<uintptr_t>(foo), a));
  EXPECT_EQ("folly::symbolizer::test::foo()", a.demangledName());

  auto path = a.location.file.toString();
  folly::StringPiece basename(path);
  auto pos = basename.rfind('/');
  if (pos != folly::StringPiece::npos) {
    basename.advance(pos + 1);
  }
  EXPECT_EQ("SymbolizerTest.cpp", basename.str());
}

FrameArray<100>* framesToFill{nullptr};

int comparator(const void* ap, const void* bp) {
  getStackTrace(*framesToFill);

  int a = *static_cast<const int*>(ap);
  int b = *static_cast<const int*>(bp);
  return a < b ? -1 : a > b ? 1 : 0;
}

// Test stack frames...
FOLLY_NOINLINE void bar();

void bar(FrameArray<100>& frames) {
  framesToFill = &frames;
  int a[2] = {1, 2};
  // Use qsort, which is in a different library
  qsort(a, 2, sizeof(int), comparator);
  framesToFill = nullptr;
}

class ElfCacheTest : public testing::Test {
 protected:
  void SetUp() override;
};

// Capture "golden" stack trace with default-configured Symbolizer
FrameArray<100> goldenFrames;

void ElfCacheTest::SetUp() {
  bar(goldenFrames);
  Symbolizer symbolizer;
  symbolizer.symbolize(goldenFrames);
  // At least 3 stack frames from us + getStackTrace()
  ASSERT_LE(4, goldenFrames.frameCount);
}

void runElfCacheTest(Symbolizer& symbolizer) {
  FrameArray<100> frames = goldenFrames;
  for (size_t i = 0; i < frames.frameCount; ++i) {
    frames.frames[i].clear();
  }
  symbolizer.symbolize(frames);
  ASSERT_LE(4, frames.frameCount);
  for (size_t i = 1; i < 4; ++i) {
    EXPECT_STREQ(goldenFrames.frames[i].name, frames.frames[i].name);
  }
}

TEST_F(ElfCacheTest, TinyElfCache) {
  ElfCache cache(1);
  Symbolizer symbolizer(&cache);
  // Run twice, in case the wrong stuff gets evicted?
  for (size_t i = 0; i < 2; ++i) {
    runElfCacheTest(symbolizer);
  }
}

TEST_F(ElfCacheTest, SignalSafeElfCache) {
  SignalSafeElfCache cache(100);
  Symbolizer symbolizer(&cache);
  for (size_t i = 0; i < 2; ++i) {
    runElfCacheTest(symbolizer);
  }
}

TEST(SymbolizerTest, SymbolCache) {
  Symbolizer symbolizer(nullptr, Dwarf::LocationInfoMode::FULL, 100);

  FrameArray<100> frames;
  bar(frames);
  symbolizer.symbolize(frames);

  FrameArray<100> frames2;
  bar(frames2);
  symbolizer.symbolize(frames2);
  for (size_t i = 0; i < frames.frameCount; i++) {
    EXPECT_STREQ(frames.frames[i].name, frames2.frames[i].name);
  }
}

} // namespace test
} // namespace symbolizer
} // namespace folly

// Can't use initFacebookLight since that would install its own signal handlers
// Can't use initFacebookNoSignals since we cannot depend on common
int main(int argc, char** argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<|endoftext|>