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

#include "binarycache.hxx"

#include "binaryreadhandler.hxx"
#include "binarywritehandler.hxx"

#include "mergedcomponentdata.hxx"

#ifndef _CONFIGMGR_FILEHELPER_HXX_
#include "filehelper.hxx"
#endif

#ifndef CONFIGMGR_TYPECONVERTER_HXX
#include "typeconverter.hxx"
#endif

#ifndef _CONFIGMGR_BOOTSTRAP_HXX
#include "bootstrap.hxx"
#endif

#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _OSL_PROCESS_H_
#include <osl/process.h>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif // _RTL_USTRBUF_HXX_

#ifndef _RTL_LOGFILE_HXX_
#include <rtl/logfile.hxx>
#endif

#define RTL_LOGFILE_OU2A(rtlOUString)   (::rtl::OUStringToOString((rtlOUString), RTL_TEXTENCODING_ASCII_US).getStr())

namespace configmgr
{
    // -----------------------------------------------------------------------------
    namespace backend
    {

        using ::rtl::OUString;

        const OUString aSettingName(
                RTL_CONSTASCII_USTRINGPARAM( CONTEXT_ITEM_PREFIX_ "CacheUrl"));
        // ---------------------------------------------------------------------------------------
        static inline bool isValidFileURL (OUString const& _sFileURL)
        {
            using osl::File;

            OUString sSystemPath;
            return _sFileURL.getLength() && (File::E_None == File::getSystemPathFromFileURL(_sFileURL, sSystemPath));
        }
        // -----------------------------------------------------------------------------
        // ---------------------------------------------------------------------------------------
        static
        bool implEnsureAbsoluteURL(rtl::OUString & _rsURL) // also strips embedded dots etc.
        {
            using osl::File;
            if (!_rsURL.getLength())
                return false;

            OSL_ENSURE(isValidFileURL(_rsURL), "File URL is invalid");

            rtl::OUString sBasePath = _rsURL;
            OSL_VERIFY(osl_Process_E_None == osl_getProcessWorkingDir(&sBasePath.pData));

            rtl::OUString sAbsolute;
            if ( File::E_None == File::getAbsoluteFileURL(sBasePath, _rsURL, sAbsolute))
            {
                _rsURL = sAbsolute;
                return isValidFileURL(_rsURL);
            }
            else
            {
                OSL_ENSURE(!isValidFileURL(_rsURL), "Could not get absolute file URL for valid URL");
                return false;
            }
        }
        // ---------------------------------------------------------------------------------------
        static const sal_Unicode kComponentSeparator = '.' ;
        static const sal_Unicode kPathSeparator = '/' ;
        static const char kBinarySuffix[] = ".dat" ;

        OUString BinaryCache::getCacheFileURL(const OUString& aComponent) const
        {
            rtl::OUStringBuffer retCode (mBaseURL);
            retCode.append(kPathSeparator) ;
        //  retCode.append(aComponent.replace(kComponentSeparator, kPathSeparator)) ;
            retCode.append(aComponent) ;
            retCode.appendAscii(RTL_CONSTASCII_STRINGPARAM(kBinarySuffix));

            OUString aResult = retCode.makeStringAndClear() ;

            if (isValidFileURL(aResult))
            {
                return aResult;
            }
            else
            {
                OSL_ENSURE(false, "Component File URL is invalid");
                return OUString();
            }
        }
        // -----------------------------------------------------------------------------
        BinaryCache::BinaryCache(const uno::Reference<uno::XComponentContext>& xContext )
        : mBaseURL()
        , mOwnerEntity()
        , mbCacheEnabled(false)
        {

            //initialise the base URL
            ContextReader aReader(xContext);

            OUString sCacheUrl;
            if (!aReader.isAdminService())
            {
                mbCacheEnabled = (aReader.getBestContext()->getValueByName(aSettingName) >>= sCacheUrl)
                                        && implEnsureAbsoluteURL(sCacheUrl);
            }

            if (mbCacheEnabled)
            {
                mBaseURL = sCacheUrl;
                if (!FileHelper::dirExists(sCacheUrl))
                {
                    if (osl::File::RC errorCode = FileHelper::mkdirs(sCacheUrl))
                    {
#if (OSL_DEBUG_LEVEL > 0)
                        rtl::OString sURL = rtl::OUStringToOString(sCacheUrl,RTL_TEXTENCODING_ASCII_US);
                        rtl::OString sErr = rtl::OUStringToOString(FileHelper::createOSLErrorString(errorCode),RTL_TEXTENCODING_ASCII_US);
                        ::osl_trace("Configuration: Cannot create cache directory \"%s\". "
                                    "Error is %s [%d]",sURL.getStr(),sErr.getStr(),int(errorCode)) ;
#endif
                        mbCacheEnabled = false;
                    }
                }
            }
        }
        // -----------------------------------------------------------------------------

        void BinaryCache::setOwnerEntity(const OUString & aOwnerEntity)
        {
            OSL_PRECOND(mOwnerEntity.getLength() == 0, "Owner entity of cache already set");
            mOwnerEntity = aOwnerEntity;
        }
        // -----------------------------------------------------------------------------

        void BinaryCache::disableCache()
        {
            mbCacheEnabled = false;
        }
        // -----------------------------------------------------------------------------

        bool BinaryCache::isCacheEnabled(rtl::OUString const & aEntity) const
        {
            if (!mbCacheEnabled) return false;

            // default entity is empty
            if (aEntity.getLength() == 0) return true;

            return aEntity.equals(mOwnerEntity);
        }
        // -----------------------------------------------------------------------------

        bool BinaryCache::readComponentData(MergedComponentData & aComponentData,
                                MultiServiceFactory const & aFactory,
                                OUString const & aComponent,
                                OUString const & aEntity,
                                OUString const & aLocale,
                                const uno::Reference<backenduno::XLayer> * pLayers,
                                sal_Int32 nNumLayers,
                                bool bIncludeTemplates)
        {
            if (isCacheEnabled(aEntity))
            try
            {
                RTL_LOGFILE_CONTEXT_AUTHOR(aLog, "configmgr::backend::BinaryCache", "jb99855", "configmgr: BinaryCache::readComponentData() - enabled");
                BinaryReadHandler aCacheReader(getCacheFileURL(aComponent),aComponent,aFactory);

                if(aCacheReader.validateHeader(pLayers, nNumLayers, mOwnerEntity, aLocale ))
                {
                    RTL_LOGFILE_CONTEXT_AUTHOR(aLog1, "configmgr::backend::BinaryCache", "jb99855", "configmgr: BinaryCache::readComponentData() - cache hit");
                    aComponentData.setSchemaRoot( aCacheReader.readComponentTree() );
                    if (bIncludeTemplates)
                        aComponentData.setTemplatesTree( aCacheReader.readTemplatesTree() );
                    return true;
                }
            }
            catch (uno::Exception & e)
            {
                OSL_TRACE("Binary Cache read failed - exception: %s", rtl::OUStringToOString(e.Message,RTL_TEXTENCODING_ASCII_US).getStr());
            }
            return false;
        }
        // -----------------------------------------------------------------------------

        bool BinaryCache::writeComponentData(MergedComponentData const & aComponentData,
                                MultiServiceFactory const & aFactory,
                                OUString const & aComponent,
                                OUString const & aEntity,
                                OUString const & aLocale,
                                const uno::Reference<backenduno::XLayer> * pLayers,
                                sal_Int32 nNumLayers)
        {
            if (isCacheEnabled(aEntity))
            try
            {
                RTL_LOGFILE_CONTEXT_AUTHOR(aLog3, "configmgr::backend::BinaryCache", "jb99855", "configmgr: BinaryCache::writeComponentData() - enabled");
                BinaryWriteHandler aCacheWriter(getCacheFileURL(aComponent),aComponent, aFactory);

                //write data to cache
                if (aCacheWriter.generateHeader(pLayers, nNumLayers, mOwnerEntity, aLocale))
                {
                    aCacheWriter.writeComponentTree(aComponentData.getSchemaTree());
                    aCacheWriter.writeTemplatesTree(aComponentData.getTemplatesTree());
                    return true;
                }
            }
            catch (uno::Exception & e)
            {
                OSL_TRACE("Configuration: Cache write failed - exception: %s", rtl::OUStringToOString(e.Message,RTL_TEXTENCODING_ASCII_US).getStr());
            }
            return false;
        }
        // -----------------------------------------------------------------------------

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

#include "binarycache.hxx"

#include "binaryreadhandler.hxx"
#include "binarywritehandler.hxx"

#include "mergedcomponentdata.hxx"

#ifndef _CONFIGMGR_FILEHELPER_HXX_
#include "filehelper.hxx"
#endif

#ifndef CONFIGMGR_TYPECONVERTER_HXX
#include "typeconverter.hxx"
#endif

#ifndef _CONFIGMGR_BOOTSTRAP_HXX
#include "bootstrap.hxx"
#endif

#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _OSL_PROCESS_H_
#include <osl/process.h>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif // _RTL_USTRBUF_HXX_

#ifndef _RTL_LOGFILE_HXX_
#include <rtl/logfile.hxx>
#endif

#define RTL_LOGFILE_OU2A(rtlOUString)   (::rtl::OUStringToOString((rtlOUString), RTL_TEXTENCODING_ASCII_US).getStr())

namespace configmgr
{
    // -----------------------------------------------------------------------------
    namespace backend
    {

        using ::rtl::OUString;

        const OUString aSettingName(
                RTL_CONSTASCII_USTRINGPARAM( CONTEXT_ITEM_PREFIX_ "CacheUrl"));
        // ---------------------------------------------------------------------------------------
        static inline bool isValidFileURL (OUString const& _sFileURL)
        {
            using osl::File;

            OUString sSystemPath;
            return _sFileURL.getLength() && (File::E_None == File::getSystemPathFromFileURL(_sFileURL, sSystemPath));
        }
        // -----------------------------------------------------------------------------
        // ---------------------------------------------------------------------------------------
        static
        bool implEnsureAbsoluteURL(rtl::OUString & _rsURL) // also strips embedded dots etc.
        {
            using osl::File;
            if (!_rsURL.getLength())
                return false;

            if (!isValidFileURL(_rsURL))
            {
                OSL_TRACE("Binary cache: File URL %s is invalid.",
                            rtl::OUStringToOString(_rsURL,RTL_TEXTENCODING_ASCII_US).getStr());
                return false;
            }

            rtl::OUString sBasePath = _rsURL;
            OSL_VERIFY(osl_Process_E_None == osl_getProcessWorkingDir(&sBasePath.pData));

            rtl::OUString sAbsolute;
            if ( File::E_None == File::getAbsoluteFileURL(sBasePath, _rsURL, sAbsolute))
            {
                _rsURL = sAbsolute;
                return isValidFileURL(_rsURL);
            }
            else
            {
                OSL_ENSURE(!isValidFileURL(_rsURL), "Could not get absolute file URL for valid URL");
                return false;
            }
        }
        // ---------------------------------------------------------------------------------------
        static const sal_Unicode kComponentSeparator = '.' ;
        static const sal_Unicode kPathSeparator = '/' ;
        static const char kBinarySuffix[] = ".dat" ;

        OUString BinaryCache::getCacheFileURL(const OUString& aComponent) const
        {
            rtl::OUStringBuffer retCode (mBaseURL);
            retCode.append(kPathSeparator) ;
        //  retCode.append(aComponent.replace(kComponentSeparator, kPathSeparator)) ;
            retCode.append(aComponent) ;
            retCode.appendAscii(RTL_CONSTASCII_STRINGPARAM(kBinarySuffix));

            OUString aResult = retCode.makeStringAndClear() ;

            if (isValidFileURL(aResult))
            {
                return aResult;
            }
            else
            {
                OSL_ENSURE(false, "Component File URL is invalid");
                return OUString();
            }
        }
        // -----------------------------------------------------------------------------
        BinaryCache::BinaryCache(const uno::Reference<uno::XComponentContext>& xContext )
        : mBaseURL()
        , mOwnerEntity()
        , mbCacheEnabled(false)
        {

            //initialise the base URL
            ContextReader aReader(xContext);

            OUString sCacheUrl;
            if (!aReader.isAdminService())
            {
                mbCacheEnabled = (aReader.getBestContext()->getValueByName(aSettingName) >>= sCacheUrl)
                                        && implEnsureAbsoluteURL(sCacheUrl);
            }

            if (mbCacheEnabled)
            {
                mBaseURL = sCacheUrl;
                if (!FileHelper::dirExists(sCacheUrl))
                {
                    if (osl::File::RC errorCode = FileHelper::mkdirs(sCacheUrl))
                    {
#if (OSL_DEBUG_LEVEL > 0)
                        rtl::OString sURL = rtl::OUStringToOString(sCacheUrl,RTL_TEXTENCODING_ASCII_US);
                        rtl::OString sErr = rtl::OUStringToOString(FileHelper::createOSLErrorString(errorCode),RTL_TEXTENCODING_ASCII_US);
                        ::osl_trace("Configuration: Cannot create cache directory \"%s\". "
                                    "Error is %s [%d]",sURL.getStr(),sErr.getStr(),int(errorCode)) ;
#endif
                        mbCacheEnabled = false;
                    }
                }
            }
        }
        // -----------------------------------------------------------------------------

        void BinaryCache::setOwnerEntity(const OUString & aOwnerEntity)
        {
            OSL_PRECOND(mOwnerEntity.getLength() == 0, "Owner entity of cache already set");
            mOwnerEntity = aOwnerEntity;
        }
        // -----------------------------------------------------------------------------

        void BinaryCache::disableCache()
        {
            mbCacheEnabled = false;
        }
        // -----------------------------------------------------------------------------

        bool BinaryCache::isCacheEnabled(rtl::OUString const & aEntity) const
        {
            if (!mbCacheEnabled) return false;

            // default entity is empty
            if (aEntity.getLength() == 0) return true;

            return aEntity.equals(mOwnerEntity);
        }
        // -----------------------------------------------------------------------------

        bool BinaryCache::readComponentData(MergedComponentData & aComponentData,
                                MultiServiceFactory const & aFactory,
                                OUString const & aComponent,
                                OUString const & aEntity,
                                OUString const & aLocale,
                                const uno::Reference<backenduno::XLayer> * pLayers,
                                sal_Int32 nNumLayers,
                                bool bIncludeTemplates)
        {
            if (isCacheEnabled(aEntity))
            try
            {
                RTL_LOGFILE_CONTEXT_AUTHOR(aLog, "configmgr::backend::BinaryCache", "jb99855", "configmgr: BinaryCache::readComponentData() - enabled");
                BinaryReadHandler aCacheReader(getCacheFileURL(aComponent),aComponent,aFactory);

                if(aCacheReader.validateHeader(pLayers, nNumLayers, mOwnerEntity, aLocale ))
                {
                    RTL_LOGFILE_CONTEXT_AUTHOR(aLog1, "configmgr::backend::BinaryCache", "jb99855", "configmgr: BinaryCache::readComponentData() - cache hit");
                    aComponentData.setSchemaRoot( aCacheReader.readComponentTree() );
                    if (bIncludeTemplates)
                        aComponentData.setTemplatesTree( aCacheReader.readTemplatesTree() );
                    return true;
                }
            }
            catch (uno::Exception & e)
            {
                OSL_TRACE("Binary Cache read failed - exception: %s", rtl::OUStringToOString(e.Message,RTL_TEXTENCODING_ASCII_US).getStr());
            }
            return false;
        }
        // -----------------------------------------------------------------------------

        bool BinaryCache::writeComponentData(MergedComponentData const & aComponentData,
                                MultiServiceFactory const & aFactory,
                                OUString const & aComponent,
                                OUString const & aEntity,
                                OUString const & aLocale,
                                const uno::Reference<backenduno::XLayer> * pLayers,
                                sal_Int32 nNumLayers)
        {
            if (isCacheEnabled(aEntity))
            try
            {
                RTL_LOGFILE_CONTEXT_AUTHOR(aLog3, "configmgr::backend::BinaryCache", "jb99855", "configmgr: BinaryCache::writeComponentData() - enabled");
                BinaryWriteHandler aCacheWriter(getCacheFileURL(aComponent),aComponent, aFactory);

                //write data to cache
                if (aCacheWriter.generateHeader(pLayers, nNumLayers, mOwnerEntity, aLocale))
                {
                    aCacheWriter.writeComponentTree(aComponentData.getSchemaTree());
                    aCacheWriter.writeTemplatesTree(aComponentData.getTemplatesTree());
                    return true;
                }
            }
            catch (uno::Exception & e)
            {
                OSL_TRACE("Configuration: Cache write failed - exception: %s", rtl::OUStringToOString(e.Message,RTL_TEXTENCODING_ASCII_US).getStr());
            }
            return false;
        }
        // -----------------------------------------------------------------------------

    }
// -----------------------------------------------------------------------------
}
<|endoftext|>


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

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

#include "cacheline.hxx"

#ifndef CONFIGMGR_SETNODEACCESS_HXX
#include "setnodeaccess.hxx"
#endif
#ifndef CONFIGMGR_TREEACCESSOR_HXX
#include "treeaccessor.hxx"
#endif
#ifndef CONFIGMGR_BUILDDATA_HXX
#include "builddata.hxx"
#endif

#ifndef CONFIGMGR_TREE_CHANGEFACTORY_HXX
#include "treechangefactory.hxx"
#endif
#ifndef INCLUDED_CONFIGMGR_MERGECHANGE_HXX
#include "mergechange.hxx"
#endif
#ifndef CONFIGMGR_CONFIGEXCEPT_HXX_
#include "configexcept.hxx"
#endif

#ifndef _CONFIGMGR_TRACER_HXX_
#include "tracer.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

namespace configmgr
{
// -----------------------------------------------------------------------------
    static inline CacheLine::Name implExtractModuleName(CacheLine::Path const& _aConfigPath)
    {
        return _aConfigPath.getModuleName();
    }

// -----------------------------------------------------------------------------
// class CacheLine
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------

    CacheLine::CacheLine(Name const & _aModuleName)
    : m_base(NULL)
    , m_name(_aModuleName)
    , m_nDataRefs(0)
    {
    }
// -----------------------------------------------------------------------------

    CacheLine::CacheLine(Name const & _aModuleName, data::TreeAddress _pSegment)
    : m_base(_pSegment)
    , m_name(_aModuleName)
    , m_nDataRefs(0)
    {
    }

// -----------------------------------------------------------------------------

    void CacheLine::setBase(data::TreeAddress _base)
    {
        OSL_PRECOND(m_base == NULL, "CacheLine: Data base address was already set");
        OSL_PRECOND( _base != NULL, "CacheLine: Cannot set NULL base address");
        m_base = _base;
    }
// -----------------------------------------------------------------------------

    CacheLineRef CacheLine::createAttached( Name const & _aModuleName,
                                            data::TreeAddress _aSegment
                                          ) CFG_UNO_THROW_RTE(  )
    {
        if (_aModuleName.isEmpty())
        {
            OSL_ENSURE(false, "Cannot make a cache line without a name");
            return NULL;
        }
        if (_aSegment == NULL)
        {
            OSL_ENSURE(false, "Cannot attach a cache line to a NULL segment");
            return NULL;
        }

        CacheLineRef xResult = new CacheLine(_aModuleName,_aSegment);

        return xResult;
    }
// -----------------------------------------------------------------------------

    CacheLineRef CacheLine::createNew(  Name const & _aModuleName
                                      ) CFG_UNO_THROW_RTE(  )
    {
        if (_aModuleName.isEmpty())
        {
            OSL_ENSURE(false, "Cannot make a cache line without a name");
            return NULL;
        }

        CacheLineRef xResult = new CacheLine(_aModuleName);

        return xResult;
    }
// -------------------------------------------------------------------------

    CacheLine::Name CacheLine::getModuleName() const
    {
        return m_name;
    }
// -----------------------------------------------------------------------------

    data::TreeAddress CacheLine::getPartialTree(Path const& aConfigName) const
    {
        data::SetNodeAccess aParentSet( internalGetNode(aConfigName.getParentPath()) );

        if (aParentSet.isValid())
            return aParentSet.getElementTree(aConfigName.getLocalName().getName());
        else
            return NULL;
    }
// -----------------------------------------------------------------------------

    bool CacheLine::hasDefaults() const
    {
    if ( m_base != NULL ) return false; // cannot get defaults without data

        data::TreeAccessor aModuleTree(m_base);
    OSL_ASSERT( aModuleTree != NULL);

        return aModuleTree->hasDefaultsAvailable();
    }
// -----------------------------------------------------------------------------
    data::NodeAccess CacheLine::internalGetNode(Path const& aConfigName) const
    {
    OSL_ENSURE( m_base != NULL, "Cannot get a node from a dataless module");

        data::TreeAccessor aModuleTree(m_base);
    OSL_ASSERT(aModuleTree != NULL);

        data::NodeAccess aNode = aModuleTree.getRootNode();
    OSL_ENSURE( aNode.isValid(), "CacheLine contains no nodes");

    Path::Iterator it = aConfigName.begin();
    OSL_ENSURE( it != aConfigName.end(), "Empty Path can't match any module");
    OSL_ENSURE( aNode.isValid() && aNode.getName() == it->getInternalName(), "Module part in config path does not match selected CacheLine");

        // find child of node
        // might be done using a visitor
    while(aNode.isValid() && ++it != aConfigName.end())
    {
            aNode = data::getSubnode(aNode,it->getName());
    }
        return aNode;
    }
// -----------------------------------------------------------------------------

    data::NodeAddress CacheLine::getNode(Path const& aConfigName) const
    {
        data::NodeAccess aNode = internalGetNode(aConfigName);
        return aNode;
    }
// -------------------------------------------------------------------------

    data::TreeAddress CacheLine::setComponentData( backend::ComponentData const & _aComponentInstance,
                                                   bool _bWithDefaults
                                                   ) CFG_UNO_THROW_RTE(  )
    {
        OSL_PRECOND(_aComponentInstance.data.get(), "CacheLine::insertDefaults: inserting NULL defaults !");
        OSL_PRECOND(_aComponentInstance.name == this->getModuleName(),"Data location does not match module");

        OSL_PRECOND(base() == NULL, "Data is already loaded");

        if (base() == NULL) // no data yet
        {
            this->setBase( data::buildTree(_aComponentInstance.data->getName(), *_aComponentInstance.data, _bWithDefaults) );
        }

        return this->base();
    }
// -----------------------------------------------------------------------------

    data::TreeAddress CacheLine::insertDefaults( backend::NodeInstance const & _aDefaultInstance
                                               ) CFG_UNO_THROW_RTE(  )
    {
        OSL_PRECOND(_aDefaultInstance.data().get(), "CacheLine::insertDefaults: inserting NULL defaults !");
        OSL_PRECOND(_aDefaultInstance.root().isModuleRoot(), "Should have complete component to fill tree with defaults");
        OSL_PRECOND(_aDefaultInstance.root().getModuleName() == this->getModuleName(),"Data location does not match module");

        OSL_PRECOND(m_base != NULL, "Data must already be loaded to insert defaults");

        if (m_base != NULL)
        {
            data::mergeDefaults(m_base,*_aDefaultInstance.data());
        }

        return m_base;
    }
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------

    ExtendedCacheLine::ExtendedCacheLine(Name const & _aModuleName)
    : CacheLine(_aModuleName)
    , m_pPending()
    {
    }

// -----------------------------------------------------------------------------

    ExtendedCacheLine::ExtendedCacheLine(Name const & _aModuleName,
                                         data::TreeAddress _aSegment)
    : CacheLine(_aModuleName,_aSegment)
    , m_pPending()
    {
    }

// -----------------------------------------------------------------------------

    ExtendedCacheLineRef ExtendedCacheLine::createAttached( Name const & _aModuleName,
                                                            data::TreeAddress _aSegment
                                                          ) CFG_UNO_THROW_RTE(  )
    {
        if (_aModuleName.isEmpty())
        {
            OSL_ENSURE(false, "Cannot make a cache line without a name");
            return NULL;
        }
        if (_aSegment == NULL)
        {
            OSL_ENSURE(false, "Cannot attach a cache line to a NULL segment");
            return NULL;
        }

        ExtendedCacheLineRef xResult = new ExtendedCacheLine(_aModuleName,_aSegment);

        return xResult;
    }
// -----------------------------------------------------------------------------

ExtendedCacheLineRef ExtendedCacheLine::createNew(  Name const & _aModuleName
                                                      ) CFG_UNO_THROW_RTE(  )
    {
        if (_aModuleName.isEmpty())
        {
            OSL_ENSURE(false, "Cannot make a cache line without a name");
            return NULL;
        }

        ExtendedCacheLineRef xResult = new ExtendedCacheLine(_aModuleName);

        return xResult;
    }
// -------------------------------------------------------------------------

    void ExtendedCacheLine::addPending(backend::ConstUpdateInstance const & _anUpdate) CFG_UNO_THROW_RTE(  )
    {
        Path aRootLocation = _anUpdate.root().location();

        OSL_PRECOND(!aRootLocation.isRoot(),"Pending change cannot be located at root");
        OSL_PRECOND(aRootLocation.getModuleName() == this->getModuleName(),"Pending change location does not match module");

        OSL_PRECOND(_anUpdate.data() != NULL,"Adding NULL 'pending' change");
        OSL_PRECOND(_anUpdate.data()->getNodeName() == aRootLocation.getLocalName().getName().toString(),
                    "Path to pending change does not match change name");

        using std::auto_ptr;

        // first make the _pSubtreeChange a full tree starting at the module root
        auto_ptr<SubtreeChange> pRootChange;
        SubtreeChange *pExistingEntry = NULL;

        Path::Iterator last = aRootLocation.end();

        OSL_ASSERT(last != aRootLocation.begin());
        --last;

        for (Path::Iterator it = aRootLocation.begin();
             it != last;
             ++it)
        {
            OSL_ASSERT( it   != aRootLocation.end());
            OSL_ASSERT( it+1 != aRootLocation.end());
            // We need to create a new SubtreeChange
            Name const aChangeName      = it->getName();
            Name const aElementTypeName = (it+1)->getTypeName();

            auto_ptr<SubtreeChange> pNewChange =
                        OTreeChangeFactory::createDummyChange(aChangeName, aElementTypeName);

            if (pExistingEntry == NULL)
            {
                OSL_ASSERT(pRootChange.get() == NULL);

                pRootChange     = pNewChange;
                pExistingEntry  = pRootChange.get();
            }
            else
            {
                OSL_ASSERT(pRootChange.get() != NULL);

                pExistingEntry->addChange(base_ptr(pNewChange));

                Change* pChange = pExistingEntry->getChange(aChangeName.toString());
                pExistingEntry = static_cast<SubtreeChange*>(pChange);

                OSL_ENSURE(pChange && pChange->ISA(SubtreeChange), "ERROR: Cannot recover change just added");
            }
        }

        auto_ptr<SubtreeChange> pAddedChange( new SubtreeChange(*_anUpdate.data(), SubtreeChange::DeepChildCopy()) );

        if (aRootLocation.getDepth() > 1)
        {
            OSL_ASSERT(pRootChange.get() != NULL && pExistingEntry != NULL);

            // the _pSubtreeChange did not start at root, so add its clone to the built dummies
            pExistingEntry->addChange(base_ptr(pAddedChange));
        }
        else
        {
            OSL_ASSERT(pRootChange.get() == NULL && pExistingEntry == NULL);

            // the _pSubtreeChange starts at root, so just reset pRootChange
            pRootChange = pAddedChange;
        }
        OSL_ASSERT(pRootChange.get() != NULL);

        if (m_pPending.get() == NULL)
        {
            // no merge is need, because the existing pending changes are empty
            m_pPending = pRootChange;
        }
        else
        {
            try
            {
                // We need to merge the new rebased changes into the m_pPending
                combineUpdates(*pRootChange,*m_pPending);
            }
            catch (configuration::Exception& e)
            {
                OUString sMessage(RTL_CONSTASCII_USTRINGPARAM("Update cache for module: Could not add pending changes at"));

                sMessage += aRootLocation.toString();

                sMessage += OUString(RTL_CONSTASCII_USTRINGPARAM(". Internal Exception:")) + e.message();

                throw uno::RuntimeException(sMessage,0);
            }
        }

        OSL_POSTCOND(m_pPending.get() != NULL, "Could not insert new pending changes");
    }
// -----------------------------------------------------------------------------

} // namespace configmgr

<commit_msg>INTEGRATION: CWS changefileheader (1.10.16); FILE MERGED 2008/04/01 15:06:54 thb 1.10.16.3: #i85898# Stripping all external header guards 2008/04/01 12:27:34 thb 1.10.16.2: #i85898# Stripping all external header guards 2008/03/31 12:22:53 rt 1.10.16.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: cacheline.cxx,v $
 * $Revision: 1.11 $
 *
 * 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_configmgr.hxx"

#include "cacheline.hxx"
#include "setnodeaccess.hxx"
#include "treeaccessor.hxx"
#include "builddata.hxx"
#include "treechangefactory.hxx"
#include "mergechange.hxx"
#include "configexcept.hxx"
#include "tracer.hxx"
#include <osl/diagnose.h>

namespace configmgr
{
// -----------------------------------------------------------------------------
    static inline CacheLine::Name implExtractModuleName(CacheLine::Path const& _aConfigPath)
    {
        return _aConfigPath.getModuleName();
    }

// -----------------------------------------------------------------------------
// class CacheLine
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------

    CacheLine::CacheLine(Name const & _aModuleName)
    : m_base(NULL)
    , m_name(_aModuleName)
    , m_nDataRefs(0)
    {
    }
// -----------------------------------------------------------------------------

    CacheLine::CacheLine(Name const & _aModuleName, data::TreeAddress _pSegment)
    : m_base(_pSegment)
    , m_name(_aModuleName)
    , m_nDataRefs(0)
    {
    }

// -----------------------------------------------------------------------------

    void CacheLine::setBase(data::TreeAddress _base)
    {
        OSL_PRECOND(m_base == NULL, "CacheLine: Data base address was already set");
        OSL_PRECOND( _base != NULL, "CacheLine: Cannot set NULL base address");
        m_base = _base;
    }
// -----------------------------------------------------------------------------

    CacheLineRef CacheLine::createAttached( Name const & _aModuleName,
                                            data::TreeAddress _aSegment
                                          ) CFG_UNO_THROW_RTE(  )
    {
        if (_aModuleName.isEmpty())
        {
            OSL_ENSURE(false, "Cannot make a cache line without a name");
            return NULL;
        }
        if (_aSegment == NULL)
        {
            OSL_ENSURE(false, "Cannot attach a cache line to a NULL segment");
            return NULL;
        }

        CacheLineRef xResult = new CacheLine(_aModuleName,_aSegment);

        return xResult;
    }
// -----------------------------------------------------------------------------

    CacheLineRef CacheLine::createNew(  Name const & _aModuleName
                                      ) CFG_UNO_THROW_RTE(  )
    {
        if (_aModuleName.isEmpty())
        {
            OSL_ENSURE(false, "Cannot make a cache line without a name");
            return NULL;
        }

        CacheLineRef xResult = new CacheLine(_aModuleName);

        return xResult;
    }
// -------------------------------------------------------------------------

    CacheLine::Name CacheLine::getModuleName() const
    {
        return m_name;
    }
// -----------------------------------------------------------------------------

    data::TreeAddress CacheLine::getPartialTree(Path const& aConfigName) const
    {
        data::SetNodeAccess aParentSet( internalGetNode(aConfigName.getParentPath()) );

        if (aParentSet.isValid())
            return aParentSet.getElementTree(aConfigName.getLocalName().getName());
        else
            return NULL;
    }
// -----------------------------------------------------------------------------

    bool CacheLine::hasDefaults() const
    {
    if ( m_base != NULL ) return false; // cannot get defaults without data

        data::TreeAccessor aModuleTree(m_base);
    OSL_ASSERT( aModuleTree != NULL);

        return aModuleTree->hasDefaultsAvailable();
    }
// -----------------------------------------------------------------------------
    data::NodeAccess CacheLine::internalGetNode(Path const& aConfigName) const
    {
    OSL_ENSURE( m_base != NULL, "Cannot get a node from a dataless module");

        data::TreeAccessor aModuleTree(m_base);
    OSL_ASSERT(aModuleTree != NULL);

        data::NodeAccess aNode = aModuleTree.getRootNode();
    OSL_ENSURE( aNode.isValid(), "CacheLine contains no nodes");

    Path::Iterator it = aConfigName.begin();
    OSL_ENSURE( it != aConfigName.end(), "Empty Path can't match any module");
    OSL_ENSURE( aNode.isValid() && aNode.getName() == it->getInternalName(), "Module part in config path does not match selected CacheLine");

        // find child of node
        // might be done using a visitor
    while(aNode.isValid() && ++it != aConfigName.end())
    {
            aNode = data::getSubnode(aNode,it->getName());
    }
        return aNode;
    }
// -----------------------------------------------------------------------------

    data::NodeAddress CacheLine::getNode(Path const& aConfigName) const
    {
        data::NodeAccess aNode = internalGetNode(aConfigName);
        return aNode;
    }
// -------------------------------------------------------------------------

    data::TreeAddress CacheLine::setComponentData( backend::ComponentData const & _aComponentInstance,
                                                   bool _bWithDefaults
                                                   ) CFG_UNO_THROW_RTE(  )
    {
        OSL_PRECOND(_aComponentInstance.data.get(), "CacheLine::insertDefaults: inserting NULL defaults !");
        OSL_PRECOND(_aComponentInstance.name == this->getModuleName(),"Data location does not match module");

        OSL_PRECOND(base() == NULL, "Data is already loaded");

        if (base() == NULL) // no data yet
        {
            this->setBase( data::buildTree(_aComponentInstance.data->getName(), *_aComponentInstance.data, _bWithDefaults) );
        }

        return this->base();
    }
// -----------------------------------------------------------------------------

    data::TreeAddress CacheLine::insertDefaults( backend::NodeInstance const & _aDefaultInstance
                                               ) CFG_UNO_THROW_RTE(  )
    {
        OSL_PRECOND(_aDefaultInstance.data().get(), "CacheLine::insertDefaults: inserting NULL defaults !");
        OSL_PRECOND(_aDefaultInstance.root().isModuleRoot(), "Should have complete component to fill tree with defaults");
        OSL_PRECOND(_aDefaultInstance.root().getModuleName() == this->getModuleName(),"Data location does not match module");

        OSL_PRECOND(m_base != NULL, "Data must already be loaded to insert defaults");

        if (m_base != NULL)
        {
            data::mergeDefaults(m_base,*_aDefaultInstance.data());
        }

        return m_base;
    }
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------

    ExtendedCacheLine::ExtendedCacheLine(Name const & _aModuleName)
    : CacheLine(_aModuleName)
    , m_pPending()
    {
    }

// -----------------------------------------------------------------------------

    ExtendedCacheLine::ExtendedCacheLine(Name const & _aModuleName,
                                         data::TreeAddress _aSegment)
    : CacheLine(_aModuleName,_aSegment)
    , m_pPending()
    {
    }

// -----------------------------------------------------------------------------

    ExtendedCacheLineRef ExtendedCacheLine::createAttached( Name const & _aModuleName,
                                                            data::TreeAddress _aSegment
                                                          ) CFG_UNO_THROW_RTE(  )
    {
        if (_aModuleName.isEmpty())
        {
            OSL_ENSURE(false, "Cannot make a cache line without a name");
            return NULL;
        }
        if (_aSegment == NULL)
        {
            OSL_ENSURE(false, "Cannot attach a cache line to a NULL segment");
            return NULL;
        }

        ExtendedCacheLineRef xResult = new ExtendedCacheLine(_aModuleName,_aSegment);

        return xResult;
    }
// -----------------------------------------------------------------------------

ExtendedCacheLineRef ExtendedCacheLine::createNew(  Name const & _aModuleName
                                                      ) CFG_UNO_THROW_RTE(  )
    {
        if (_aModuleName.isEmpty())
        {
            OSL_ENSURE(false, "Cannot make a cache line without a name");
            return NULL;
        }

        ExtendedCacheLineRef xResult = new ExtendedCacheLine(_aModuleName);

        return xResult;
    }
// -------------------------------------------------------------------------

    void ExtendedCacheLine::addPending(backend::ConstUpdateInstance const & _anUpdate) CFG_UNO_THROW_RTE(  )
    {
        Path aRootLocation = _anUpdate.root().location();

        OSL_PRECOND(!aRootLocation.isRoot(),"Pending change cannot be located at root");
        OSL_PRECOND(aRootLocation.getModuleName() == this->getModuleName(),"Pending change location does not match module");

        OSL_PRECOND(_anUpdate.data() != NULL,"Adding NULL 'pending' change");
        OSL_PRECOND(_anUpdate.data()->getNodeName() == aRootLocation.getLocalName().getName().toString(),
                    "Path to pending change does not match change name");

        using std::auto_ptr;

        // first make the _pSubtreeChange a full tree starting at the module root
        auto_ptr<SubtreeChange> pRootChange;
        SubtreeChange *pExistingEntry = NULL;

        Path::Iterator last = aRootLocation.end();

        OSL_ASSERT(last != aRootLocation.begin());
        --last;

        for (Path::Iterator it = aRootLocation.begin();
             it != last;
             ++it)
        {
            OSL_ASSERT( it   != aRootLocation.end());
            OSL_ASSERT( it+1 != aRootLocation.end());
            // We need to create a new SubtreeChange
            Name const aChangeName      = it->getName();
            Name const aElementTypeName = (it+1)->getTypeName();

            auto_ptr<SubtreeChange> pNewChange =
                        OTreeChangeFactory::createDummyChange(aChangeName, aElementTypeName);

            if (pExistingEntry == NULL)
            {
                OSL_ASSERT(pRootChange.get() == NULL);

                pRootChange     = pNewChange;
                pExistingEntry  = pRootChange.get();
            }
            else
            {
                OSL_ASSERT(pRootChange.get() != NULL);

                pExistingEntry->addChange(base_ptr(pNewChange));

                Change* pChange = pExistingEntry->getChange(aChangeName.toString());
                pExistingEntry = static_cast<SubtreeChange*>(pChange);

                OSL_ENSURE(pChange && pChange->ISA(SubtreeChange), "ERROR: Cannot recover change just added");
            }
        }

        auto_ptr<SubtreeChange> pAddedChange( new SubtreeChange(*_anUpdate.data(), SubtreeChange::DeepChildCopy()) );

        if (aRootLocation.getDepth() > 1)
        {
            OSL_ASSERT(pRootChange.get() != NULL && pExistingEntry != NULL);

            // the _pSubtreeChange did not start at root, so add its clone to the built dummies
            pExistingEntry->addChange(base_ptr(pAddedChange));
        }
        else
        {
            OSL_ASSERT(pRootChange.get() == NULL && pExistingEntry == NULL);

            // the _pSubtreeChange starts at root, so just reset pRootChange
            pRootChange = pAddedChange;
        }
        OSL_ASSERT(pRootChange.get() != NULL);

        if (m_pPending.get() == NULL)
        {
            // no merge is need, because the existing pending changes are empty
            m_pPending = pRootChange;
        }
        else
        {
            try
            {
                // We need to merge the new rebased changes into the m_pPending
                combineUpdates(*pRootChange,*m_pPending);
            }
            catch (configuration::Exception& e)
            {
                OUString sMessage(RTL_CONSTASCII_USTRINGPARAM("Update cache for module: Could not add pending changes at"));

                sMessage += aRootLocation.toString();

                sMessage += OUString(RTL_CONSTASCII_USTRINGPARAM(". Internal Exception:")) + e.message();

                throw uno::RuntimeException(sMessage,0);
            }
        }

        OSL_POSTCOND(m_pPending.get() != NULL, "Could not insert new pending changes");
    }
// -----------------------------------------------------------------------------

} // namespace configmgr

<|endoftext|>


<commit_before>// Author: Chrono Law
// Copyright (c) 2015
#ifndef _NGX_BUF_HPP
#define _NGX_BUF_HPP

#include "NgxPool.hpp"

class NgxBuf final : public NgxWrapper<ngx_buf_t>
{
public:
    typedef NgxWrapper<ngx_buf_t> super_type;
    typedef NgxBuf this_type;
public:
    NgxBuf(const NgxPool& p, std::size_t n):
        super_type(p.buffer(n))
    {}

    NgxBuf(ngx_buf_t* buf):super_type(buf)
    {}

    ~NgxBuf() = default;
public:
    // readable range
    void range(u_char* a, u_char* b) const
    {
        get()->pos = a;
        get()->last = b;

        get()->memory = true;
    }

    // convenitable method
    void range(ngx_str_t* s) const
    {
        range(s->data, s->data + s->len);
        boundary(s->data, s->data + s->len);
    }

    void boundary(u_char* a, u_char* b) const
    {
        get()->start = a;
        get()->end = b;
    }

    ngx_str_t range() const
    {
        return ngx_str_t{
            static_cast<std::size_t>(get()->last - get()->pos), get()->pos};
    }

    ngx_str_t boundary() const
    {
        return ngx_str_t{
            static_cast<std::size_t>(get()->end - get()->start), get()->start};
    }
public:
    template<typename ... Args>
    void printf(const Args& ... args) const
    {
        get()->last = ngx_slprintf(get()->pos, get()->end, args ...);
    }

    void copy(u_char* src, size_t n) const
    {
        get()->last = ngx_copy(get()->pos, src, n);
    }
public:
    std::size_t size() const
    {
        return ngx_buf_size(get());
    }

    void clear() const
    {
        get()->pos = get()->last;
    }

    void reset() const
    {
        get()->pos = get()->start;
        get()->last = get()->start;
    }

//    ngx_uint_t capacity() const
//    {
//        return get()->end - get()->start;
//    }

public:
    bool empty() const
    {
        return get()->pos == get()->last;
    }

    bool full() const
    {
        return get()->pos == get()->end;
    }
public:
    void consume(std::size_t n) const
    {
        if(n > size())
        {
            n = size();
        }

        get()->pos += n;
    }

    void produce(std::size_t n) const
    {
        get()->last += n;

        if(get()->last > get()->end)
        {
            get()->last = get()->end;
        }
    }
public:
    u_char* begin() const
    {
        return get()->pos;
    }

    u_char* end() const
    {
        return get()->last;
    }
public:
    bool memory() const
    {
        return ngx_buf_in_memory(get());
    }

    bool memoryonly() const
    {
        return ngx_buf_in_memory_only(get());
    }

    bool special() const
    {
        return ngx_buf_special(get());
    }
public:
    bool last() const
    {
        return get()->last_buf || get()->last_in_chain;
    }

    void finish(bool flag = true) const
    {
        get()->last_buf = flag;
        get()->last_in_chain = flag;
    }
};

#include <boost/iterator/iterator_facade.hpp>
#include <boost/core/explicit_operator_bool.hpp>

class NgxChainNode final : public NgxWrapper<ngx_chain_t>
{
public:
    typedef NgxWrapper<ngx_chain_t> super_type;
    typedef NgxChainNode this_type;
public:
    NgxChainNode(const NgxPool& p):super_type(p.chain())
    {}

    NgxChainNode(ngx_chain_t* c):super_type(c)
    {}

    ~NgxChainNode() = default;
public:
    bool last() const
    {
        return !get()->next;
    }

    void link(ngx_chain_t* c) const
    {
        get()->next = c;
    }

    void finish() const
    {
        return link(nullptr);
    }
public:
    NgxBuf data() const
    {
        return get()->buf;
    }

    void set(ngx_buf_t* ptr) const
    {
        get()->buf = ptr;
    }
};

class NgxChainIterator final:
        public boost::iterator_facade<
                    NgxChainIterator, NgxChainNode,
                    boost::single_pass_traversal_tag>
{
public:
    typedef boost::iterator_facade<
                    NgxChainIterator, NgxChainNode,
                    boost::single_pass_traversal_tag>
            super_type;
    typedef typename super_type::reference reference;
public:
    NgxChainIterator(ngx_chain_t* c) : m_p(c)
    {}

    NgxChainIterator() = default;
    ~NgxChainIterator() = default;
public:
    BOOST_EXPLICIT_OPERATOR_BOOL()

    bool operator!() const
    {
        return !m_p;
    }

private:
    friend class boost::iterator_core_access;

    reference dereference() const
    {
        m_proxy = m_p;
        return m_proxy;
    }

    void increment()
    {
        if(!m_p)
        {
            return;
        }

        m_p = m_p->next;
    }

    bool equal(NgxChainIterator const& o) const
    {
        return m_p == o.m_p;
    }
private:
    ngx_chain_t* m_p = nullptr;
    mutable NgxChainNode m_proxy{m_p};
};

class NgxChain final : public NgxWrapper<ngx_chain_t>
{
public:
    typedef NgxWrapper<ngx_chain_t> super_type;
    typedef NgxChain this_type;
public:
    NgxChain(ngx_chain_t* c):super_type(c)
    {}

    ~NgxChain() = default;
public:
    typedef NgxChainIterator iterator;
    typedef const iterator const_iterator;

    iterator begin() const
    {
        return iterator(get());
    }

    iterator end() const
    {
        return iterator();
    }
public:
    template<typename V>
    void visit(V v) const
    {
        for(auto iter = begin();
            iter; ++iter)
        {
            v(*iter);
        }
    }
public:
    std::size_t size() const
    {
        std::size_t len = 0;

        for(auto& c : *this)
        {
            len += c.data().size();
        }

        return len;
    }

    ngx_chain_t* tail() const
    {
        auto p = get();

        for(;p->next;p = p->next);

        return p;
    }

    void append(ngx_chain_t* ch) const
    {
        tail()->next = ch;
    }
public:
    void clear() const
    {
        for(auto& c : *this)
        {
            c.data().clear();
        }
    }
public:
    void copy(u_char* p) const
    {
        for(auto& c : *this)
        {
            p = ngx_copy(p, c.data().begin(), c.data().size());
        }
    }
};

#endif  //_NGX_BUF_HPP
<commit_msg>chain trace tail<commit_after>// Author: Chrono Law
// Copyright (c) 2015-2016
#ifndef _NGX_BUF_HPP
#define _NGX_BUF_HPP

#include "NgxPool.hpp"

class NgxBuf final : public NgxWrapper<ngx_buf_t>
{
public:
    typedef NgxWrapper<ngx_buf_t> super_type;
    typedef NgxBuf this_type;
public:
    NgxBuf(const NgxPool& p, std::size_t n):
        super_type(p.buffer(n))
    {}

    NgxBuf(ngx_buf_t* buf):super_type(buf)
    {}

    ~NgxBuf() = default;
public:
    // readable range
    void range(u_char* a, u_char* b) const
    {
        get()->pos = a;
        get()->last = b;

        get()->memory = true;
    }

    // convenitable method
    void range(ngx_str_t* s) const
    {
        range(s->data, s->data + s->len);
        boundary(s->data, s->data + s->len);
    }

    void boundary(u_char* a, u_char* b) const
    {
        get()->start = a;
        get()->end = b;
    }

    ngx_str_t range() const
    {
        return ngx_str_t{
            static_cast<std::size_t>(get()->last - get()->pos), get()->pos};
    }

    ngx_str_t boundary() const
    {
        return ngx_str_t{
            static_cast<std::size_t>(get()->end - get()->start), get()->start};
    }
public:
    template<typename ... Args>
    void printf(const Args& ... args) const
    {
        get()->last = ngx_slprintf(get()->pos, get()->end, args ...);
    }

    void copy(u_char* src, size_t n) const
    {
        get()->last = ngx_copy(get()->pos, src, n);
    }
public:
    std::size_t size() const
    {
        return ngx_buf_size(get());
    }

    void clear() const
    {
        get()->pos = get()->last;
    }

    void reset() const
    {
        get()->pos = get()->start;
        get()->last = get()->start;
    }

//    ngx_uint_t capacity() const
//    {
//        return get()->end - get()->start;
//    }

public:
    bool empty() const
    {
        return get()->pos == get()->last;
    }

    bool full() const
    {
        return get()->pos == get()->end;
    }
public:
    void consume(std::size_t n) const
    {
        if(n > size())
        {
            n = size();
        }

        get()->pos += n;
    }

    void produce(std::size_t n) const
    {
        get()->last += n;

        if(get()->last > get()->end)
        {
            get()->last = get()->end;
        }
    }
public:
    u_char* begin() const
    {
        return get()->pos;
    }

    u_char* end() const
    {
        return get()->last;
    }
public:
    bool memory() const
    {
        return ngx_buf_in_memory(get());
    }

    bool memoryonly() const
    {
        return ngx_buf_in_memory_only(get());
    }

    bool special() const
    {
        return ngx_buf_special(get());
    }
public:
    bool last() const
    {
        return get()->last_buf || get()->last_in_chain;
    }

    void finish(bool flag = true) const
    {
        get()->last_buf = flag;
        get()->last_in_chain = flag;
    }
};

#include <boost/iterator/iterator_facade.hpp>
#include <boost/core/explicit_operator_bool.hpp>

class NgxChainNode final : public NgxWrapper<ngx_chain_t>
{
public:
    typedef NgxWrapper<ngx_chain_t> super_type;
    typedef NgxChainNode this_type;
public:
    NgxChainNode(const NgxPool& p):super_type(p.chain())
    {}

    NgxChainNode(ngx_chain_t* c):super_type(c)
    {}

    ~NgxChainNode() = default;
public:
    bool last() const
    {
        return !get()->next;
    }

    void link(ngx_chain_t* c) const
    {
        get()->next = c;
    }

    void finish() const
    {
        return link(nullptr);
    }
public:
    NgxBuf data() const
    {
        return get()->buf;
    }

    void set(ngx_buf_t* ptr) const
    {
        get()->buf = ptr;
    }
};

class NgxChainIterator final:
        public boost::iterator_facade<
                    NgxChainIterator, NgxChainNode,
                    boost::single_pass_traversal_tag>
{
public:
    typedef boost::iterator_facade<
                    NgxChainIterator, NgxChainNode,
                    boost::single_pass_traversal_tag>
            super_type;
    typedef typename super_type::reference reference;
public:
    NgxChainIterator(ngx_chain_t* c) : m_p(c)
    {}

    NgxChainIterator() = default;
    ~NgxChainIterator() = default;
public:
    BOOST_EXPLICIT_OPERATOR_BOOL()

    bool operator!() const
    {
        return !m_p;
    }

private:
    friend class boost::iterator_core_access;

    reference dereference() const
    {
        m_proxy = m_p;
        return m_proxy;
    }

    void increment()
    {
        if(!m_p)
        {
            return;
        }

        m_p = m_p->next;
    }

    bool equal(NgxChainIterator const& o) const
    {
        return m_p == o.m_p;
    }
private:
    ngx_chain_t* m_p = nullptr;
    mutable NgxChainNode m_proxy{m_p};
};

class NgxChain final : public NgxWrapper<ngx_chain_t>
{
public:
    typedef NgxWrapper<ngx_chain_t> super_type;
    typedef NgxChain this_type;
public:
    NgxChain(ngx_chain_t* c):super_type(c)
    {}

    ~NgxChain() = default;
public:
    typedef NgxChainIterator iterator;
    typedef const iterator const_iterator;

    iterator begin() const
    {
        return iterator(get());
    }

    iterator end() const
    {
        return iterator();
    }
public:
    template<typename V>
    void visit(V v) const
    {
        for(auto iter = begin();
            iter; ++iter)
        {
            v(*iter);
        }
    }
public:
    std::size_t size() const
    {
        std::size_t len = 0;

        for(auto& c : *this)
        {
            len += c.data().size();
        }

        return len;
    }

public:
    ngx_chain_t* head() const
    {
        return get();
    }

    ngx_chain_t* tail() const
    {
        auto p = get();

        for(;p->next;p = p->next);

        return p;
    }

    void append(ngx_chain_t* ch) const
    {
        tail()->next = ch;
    }

public:
    // V is a lambda
    // [](ngx_chain_t* c){}
    // [](const NgxChainNode& c){}
    template<typename V>
    iterator trace_tail(V v) const
    {
        auto p = get();

        for(;p->next;p = p->next)
        {
            v(p);
        }

        v(p);   // last node

        return p;
    }
public:
    void clear() const
    {
        for(auto& c : *this)
        {
            c.data().clear();
        }
    }
public:
    void copy(u_char* p) const
    {
        for(auto& c : *this)
        {
            p = ngx_copy(p, c.data().begin(), c.data().size());
        }
    }
};

#endif  //_NGX_BUF_HPP
<|endoftext|>


<commit_before>/*
* Copyright (c) 2007-2011 SlimDX Group
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "stdafx.h"

using namespace System;
using namespace System::Resources;
using namespace System::Reflection;
using namespace System::Runtime::CompilerServices;
using namespace System::Runtime::InteropServices;
using namespace System::Security::Permissions;

//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly:AssemblyTitleAttribute("SlimDX")];
[assembly:AssemblyDescriptionAttribute("Provides a managed wrapper around Microsoft DirectX.")];
[assembly:AssemblyConfigurationAttribute("")];
[assembly:AssemblyCompanyAttribute("SlimDX Group")];
[assembly:AssemblyProductAttribute("SlimDX")];
[assembly:AssemblyCopyrightAttribute("Copyright  2007-2011 SlimDX Group")];
[assembly:AssemblyTrademarkAttribute("")];
[assembly:AssemblyCultureAttribute("")];

//
// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the value or you can default the Revision and Build Numbers
// by using the '*' as shown below:

#if _MSC_VER < 1600
[assembly:AssemblyVersionAttribute("2.0.12.43")];
#else
[assembly:AssemblyVersionAttribute("4.0.12.43")];
#endif

[assembly:ComVisible(false)];

[assembly:CLSCompliantAttribute(true)];

[assembly:NeutralResourcesLanguageAttribute("en-US")]

[assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)];

#ifndef PUBLIC
[assembly:InternalsVisibleTo("SlimDX.Tests")];
#endif<commit_msg>Updated project version number to 13 for Jan 2012 release (continued).<commit_after>/*
* Copyright (c) 2007-2011 SlimDX Group
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "stdafx.h"

using namespace System;
using namespace System::Resources;
using namespace System::Reflection;
using namespace System::Runtime::CompilerServices;
using namespace System::Runtime::InteropServices;
using namespace System::Security::Permissions;

//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly:AssemblyTitleAttribute("SlimDX")];
[assembly:AssemblyDescriptionAttribute("Provides a managed wrapper around Microsoft DirectX.")];
[assembly:AssemblyConfigurationAttribute("")];
[assembly:AssemblyCompanyAttribute("SlimDX Group")];
[assembly:AssemblyProductAttribute("SlimDX")];
[assembly:AssemblyCopyrightAttribute("Copyright  2007-2011 SlimDX Group")];
[assembly:AssemblyTrademarkAttribute("")];
[assembly:AssemblyCultureAttribute("")];

//
// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the value or you can default the Revision and Build Numbers
// by using the '*' as shown below:

#if _MSC_VER < 1600
[assembly:AssemblyVersionAttribute("2.0.13.43")];
#else
[assembly:AssemblyVersionAttribute("4.0.13.43")];
#endif

[assembly:ComVisible(false)];

[assembly:CLSCompliantAttribute(true)];

[assembly:NeutralResourcesLanguageAttribute("en-US")]

[assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)];

#ifndef PUBLIC
[assembly:InternalsVisibleTo("SlimDX.Tests")];
#endif<|endoftext|>


<commit_before>#include "DRAMAnalyzer.h"
#include "DRAMAnalyzerSettings.h"
#include <AnalyzerChannelData.h>
#include <iostream>

DRAMAnalyzer::DRAMAnalyzer()
:	Analyzer(),
	mSettings( new DRAMAnalyzerSettings() ),
	mSimulationInitilized( false )
{
	SetAnalyzerSettings( mSettings.get() );
}

DRAMAnalyzer::~DRAMAnalyzer()
{
	KillThread();
}

void DRAMAnalyzer::WorkerThread()
{
	mResults.reset( new DRAMAnalyzerResults( this, mSettings.get() ) );
	SetAnalyzerResults( mResults.get() );
	mResults->AddChannelBubblesWillAppearOn( mSettings->mRASbChannel );

	mRASb = GetAnalyzerChannelData( mSettings->mRASbChannel );
	mCASb = GetAnalyzerChannelData( mSettings->mCASbChannel );
	mWb = GetAnalyzerChannelData( mSettings->mWbChannel );
	mOEb = GetAnalyzerChannelData( mSettings->mOEbChannel );

	bool valid_row_addr = false;

	for( ; ; ) {

	  U64 next_RAS = mRASb->GetSampleOfNextEdge();
	  U64 next_CAS = mCASb->GetSampleOfNextEdge();

	  std::cout << next_RAS << " " << next_CAS << std::endl;

	  bool prev_RASb_is_high = mRASb->GetBitState() == BIT_HIGH;
	  bool prev_CASb_is_high = mCASb->GetBitState() == BIT_HIGH;

	  if        ( next_RAS == next_CAS) {
	    mRASb->AdvanceToNextEdge();
	    mCASb->AdvanceToNextEdge();
	  } else if ( next_RAS < next_CAS) {
	    mRASb->AdvanceToNextEdge();

	    if ( prev_RASb_is_high && prev_CASb_is_high) {
	      valid_row_addr = true;
	    }

	  } else { /* next_RAS > next_CAS */
	    mCASb->AdvanceToNextEdge();

	    U64 starting_sample = mCASb->GetSampleNumber();

	    //we have a byte to save.
	    Frame frame;
	    frame.mData1 = 1;
	    frame.mFlags = 0;
	    frame.mStartingSampleInclusive = starting_sample;
	    frame.mEndingSampleInclusive = starting_sample + 1;

	    mResults->AddFrame( frame );
	    mResults->CommitResults();
	    ReportProgress( frame.mEndingSampleInclusive );
	  }

          CheckIfThreadShouldExit();
	}
}

bool DRAMAnalyzer::NeedsRerun()
{
	return false;
}

U32 DRAMAnalyzer::GenerateSimulationData( U64 minimum_sample_index, U32 device_sample_rate, SimulationChannelDescriptor** simulation_channels )
{
	if( mSimulationInitilized == false )
	{
		mSimulationDataGenerator.Initialize( GetSimulationSampleRate(), mSettings.get() );
		mSimulationInitilized = true;
	}

	return mSimulationDataGenerator.GenerateSimulationData( minimum_sample_index, device_sample_rate, simulation_channels );
}

U32 DRAMAnalyzer::GetMinimumSampleRateHz()
{
	return 100000;
}

const char* DRAMAnalyzer::GetAnalyzerName() const
{
	return "Asynchoronous DRAM Analyzer";
}

const char* GetAnalyzerName()
{
	return "Asynchoronous DRAM Analyzer";
}

Analyzer* CreateAnalyzer()
{
	return new DRAMAnalyzer();
}

void DestroyAnalyzer( Analyzer* analyzer )
{
	delete analyzer;
}
<commit_msg>Added markers for write/read transactions<commit_after>#include "DRAMAnalyzer.h"
#include "DRAMAnalyzerSettings.h"
#include <AnalyzerChannelData.h>
#include <iostream>

DRAMAnalyzer::DRAMAnalyzer()
:	Analyzer(),
	mSettings( new DRAMAnalyzerSettings() ),
	mSimulationInitilized( false )
{
	SetAnalyzerSettings( mSettings.get() );
}

DRAMAnalyzer::~DRAMAnalyzer()
{
	KillThread();
}

void DRAMAnalyzer::WorkerThread()
{
	mResults.reset( new DRAMAnalyzerResults( this, mSettings.get() ) );
	SetAnalyzerResults( mResults.get() );
	mResults->AddChannelBubblesWillAppearOn( mSettings->mCASbChannel );

	mRASb = GetAnalyzerChannelData( mSettings->mRASbChannel );
	mCASb = GetAnalyzerChannelData( mSettings->mCASbChannel );
	mWb = GetAnalyzerChannelData( mSettings->mWbChannel );
	mOEb = GetAnalyzerChannelData( mSettings->mOEbChannel );

	bool valid_row_addr = false;

	for( ; ; ) {

	  U64 next_RAS = mRASb->GetSampleOfNextEdge();
	  U64 next_CAS = mCASb->GetSampleOfNextEdge();

	  //	  std::cout << next_RAS << " " << next_CAS << std::endl;

	  bool prev_RASb_is_high = mRASb->GetBitState() == BIT_HIGH;
	  bool prev_CASb_is_high = mCASb->GetBitState() == BIT_HIGH;

	  if ( next_RAS <= next_CAS) {
	    mRASb->AdvanceToNextEdge();
	    mCASb->AdvanceToAbsPosition( mRASb->GetSampleNumber());
          } else {
	    mCASb->AdvanceToNextEdge();
	    mRASb->AdvanceToAbsPosition( mCASb->GetSampleNumber());
	  }

	  if ( prev_RASb_is_high && prev_CASb_is_high) {
	    if ( mRASb->GetBitState() == BIT_HIGH) {
	      if ( mCASb->GetBitState() == BIT_HIGH) {
		/* no transition */
	      } else {
		/* CAS */
	      }
	    } else {
	      if ( mCASb->GetBitState() == BIT_HIGH) {
		/* RAS */
		valid_row_addr = true;
	      } else {
		/* simultaneous flip */
	      }
	    }
	  } else if ( !prev_RASb_is_high &&  prev_CASb_is_high) {
	    if ( mRASb->GetBitState() == BIT_HIGH) {
	      if ( mCASb->GetBitState() == BIT_HIGH) {
		/* RASb up */
	      } else {
		/* simult */
	      }
	    } else {
	      if ( mCASb->GetBitState() == BIT_HIGH) {
		/* no transition  */
	      } else {
		/* write/read */
		U64 starting_sample = mCASb->GetSampleNumber();

		std::cout << "write/read: " << starting_sample << std::endl;

		//we have a byte to save.
		Frame frame;
		frame.mData1 = 1;
		frame.mFlags = 0;
		frame.mStartingSampleInclusive = starting_sample;
		frame.mEndingSampleInclusive = starting_sample + 100;

		mResults->AddMarker( starting_sample, AnalyzerResults::DownArrow, mSettings->mCASbChannel);
		mResults->AddFrame( frame );
		mResults->CommitResults();
		ReportProgress( frame.mEndingSampleInclusive );
	      }
	    }
	  } else if (  prev_RASb_is_high && !prev_CASb_is_high) {
	    if ( mRASb->GetBitState() == BIT_HIGH) {
	      if ( mCASb->GetBitState() == BIT_HIGH) {
		valid_row_addr = false;
	      } else {
		/* no transition */
	      }
	    } else {
	      if ( mCASb->GetBitState() == BIT_HIGH) {
		/* simultaneous flip */
	      } else {
		/* RAS down after CAS down */
	      }
	    }
	  } else if ( !prev_RASb_is_high && !prev_CASb_is_high) {
	    if ( mRASb->GetBitState() == BIT_HIGH) {
	      if ( mCASb->GetBitState() == BIT_HIGH) {
		/* simultaneous flip */
	      } else {
		/* RAS up */
	      }
	    } else {
	      if ( mCASb->GetBitState() == BIT_HIGH) {
		/* CAS up */
	      } else {
		/* no transition */
	      }
	    }
	  }

          CheckIfThreadShouldExit();
	}
}

bool DRAMAnalyzer::NeedsRerun()
{
	return false;
}

U32 DRAMAnalyzer::GenerateSimulationData( U64 minimum_sample_index, U32 device_sample_rate, SimulationChannelDescriptor** simulation_channels )
{
	if( mSimulationInitilized == false )
	{
		mSimulationDataGenerator.Initialize( GetSimulationSampleRate(), mSettings.get() );
		mSimulationInitilized = true;
	}

	return mSimulationDataGenerator.GenerateSimulationData( minimum_sample_index, device_sample_rate, simulation_channels );
}

U32 DRAMAnalyzer::GetMinimumSampleRateHz()
{
	return 100000;
}

const char* DRAMAnalyzer::GetAnalyzerName() const
{
	return "Asynchoronous DRAM Analyzer";
}

const char* GetAnalyzerName()
{
	return "Asynchoronous DRAM Analyzer";
}

Analyzer* CreateAnalyzer()
{
	return new DRAMAnalyzer();
}

void DestroyAnalyzer( Analyzer* analyzer )
{
	delete analyzer;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2008-2009 Manjeet Dahiya
 *
 * Author:
 *	Manjeet Dahiya
 *
 * Source:
 *	http://code.google.com/p/qxmpp
 *
 * This file is a part of QXmpp library.
 *
 * This library 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.1 of the License, or (at your option) any later version.
 *
 * 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.
 *
 */

#include "QXmppConstants.h"
#include "QXmppMessage.h"
#include "QXmppUtils.h"
#include <QDomElement>
#include <QXmlStreamWriter>

static const char* chat_states[] = {
    "",
    "active",
    "inactive",
    "gone",
    "composing",
    "paused",
};

QXmppMessage::QXmppMessage(const QString& from, const QString& to, const
                         QString& body, const QString& thread)
    : QXmppStanza(from, to), m_type(Chat), m_state(None), m_body(body), m_thread(thread)
{
}

QXmppMessage::~QXmppMessage()
{

}

QXmppMessage::Type QXmppMessage::getType() const
{
    return m_type;
}

QString QXmppMessage::getTypeStr() const
{
    switch(getType())
    {
    case QXmppMessage::Error:
        return "error";
    case QXmppMessage::Normal:
        return "normal";
    case QXmppMessage::Chat:
        return "chat";
    case QXmppMessage::GroupChat:
        return "groupchat";
    case QXmppMessage::Headline:
        return "headline";
    default:
        qWarning("QXmppMessage::getTypeStr() invalid type %d", (int)getType());
        return "";
    }
}

void QXmppMessage::setType(QXmppMessage::Type type)
{
    m_type = type;
}

void QXmppMessage::setTypeFromStr(const QString& str)
{
    if(str == "error")
    {
        setType(QXmppMessage::Error);
        return;
    }
    else if(str == "")   // if no type is specified
    {
        setType(QXmppMessage::Normal);
        return;
    }
    else if(str == "normal")
    {
        setType(QXmppMessage::Normal);
        return;
    }
    else if(str == "chat")
    {
        setType(QXmppMessage::Chat);
        return;
    }
    else if(str == "groupchat")
    {
        setType(QXmppMessage::GroupChat);
        return;
    }
    else if(str == "headline")
    {
        setType(QXmppMessage::Headline);
        return;
    }
    else
    {
        setType(static_cast<QXmppMessage::Type>(-1));
        qWarning("QXmppMessage::setTypeFromStr() invalid input string type: %s",
                 qPrintable(str));
        return;
    }
}

QXmppMessage::State QXmppMessage::getState() const
{
    return m_state;
}

void QXmppMessage::setState(QXmppMessage::State state)
{
    m_state = state;
}

void QXmppMessage::parse(QDomElement &element)
{
    setFrom(element.attribute("from"));
    setTo(element.attribute("to"));
    setTypeFromStr(element.attribute("type"));
    setBody(unescapeString(
            element.firstChildElement("body").text()));
    setSubject(unescapeString(
            element.firstChildElement("subject").text()));
    setThread(element.firstChildElement("thread").text());

    QDomElement errorElement = element.
                               firstChildElement("error");
    if(!errorElement.isNull())
    {
        QXmppStanza::Error error = parseError(errorElement);
        setError(error);
    }

    for (int i = Active; i <= Paused; i++)
    {
        QDomElement stateElement = element.firstChildElement(chat_states[i]);
        if (!stateElement.isNull() &&
            stateElement.namespaceURI() == ns_chat_states)
        {
            m_state = static_cast<QXmppMessage::State>(i);
            break;
        }
    }

    QDomElement xElement = element.firstChildElement("x");
    if(!xElement.isNull())
        setExtensions(QXmppElement(xElement));
}

void QXmppMessage::toXml(QXmlStreamWriter *xmlWriter) const
{

    xmlWriter->writeStartElement("message");
    helperToXmlAddAttribute(xmlWriter, "xml:lang", getLang());
    helperToXmlAddAttribute(xmlWriter,  "id", getId());
    helperToXmlAddAttribute(xmlWriter, "to", getTo());
    helperToXmlAddAttribute(xmlWriter, "from", getFrom());
    helperToXmlAddAttribute(xmlWriter,  "type", getTypeStr());
    if (!getSubject().isEmpty())
        helperToXmlAddTextElement(xmlWriter, "subject", getSubject());
    helperToXmlAddTextElement(xmlWriter,"body", getBody());
    if (!getThread().isEmpty())
        helperToXmlAddTextElement(xmlWriter,"thread", getThread());
    getError().toXml(xmlWriter);

    if (m_state > None && m_state <= Paused)
    {
        xmlWriter->writeStartElement(chat_states[m_state]);
        helperToXmlAddAttribute(xmlWriter, "xmlns", ns_chat_states);
        xmlWriter->writeEndElement();
    }

    foreach (const QXmppElement &extension, getExtensions())
        extension.toXml(xmlWriter);
    xmlWriter->writeEndElement();
}

QString QXmppMessage::getBody() const
{
    return m_body;
}

void QXmppMessage::setBody(const QString& body)
{
    m_body = body;
}

QString QXmppMessage::getSubject() const
{
    return m_subject;
}

void QXmppMessage::setSubject(const QString& sub)
{
    m_subject = sub;
}

QString QXmppMessage::getThread() const
{
    return m_thread;
}

void QXmppMessage::setThread(const QString& thread)
{
    m_thread = thread;
}

<commit_msg>* check whether body is empty before adding "body" element to a message * remove some gratuitous accessor calls<commit_after>/*
 * Copyright (C) 2008-2009 Manjeet Dahiya
 *
 * Author:
 *	Manjeet Dahiya
 *
 * Source:
 *	http://code.google.com/p/qxmpp
 *
 * This file is a part of QXmpp library.
 *
 * This library 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.1 of the License, or (at your option) any later version.
 *
 * 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.
 *
 */

#include "QXmppConstants.h"
#include "QXmppMessage.h"
#include "QXmppUtils.h"
#include <QDomElement>
#include <QXmlStreamWriter>

static const char* chat_states[] = {
    "",
    "active",
    "inactive",
    "gone",
    "composing",
    "paused",
};

QXmppMessage::QXmppMessage(const QString& from, const QString& to, const
                         QString& body, const QString& thread)
    : QXmppStanza(from, to), m_type(Chat), m_state(None), m_body(body), m_thread(thread)
{
}

QXmppMessage::~QXmppMessage()
{

}

QXmppMessage::Type QXmppMessage::getType() const
{
    return m_type;
}

QString QXmppMessage::getTypeStr() const
{
    switch(getType())
    {
    case QXmppMessage::Error:
        return "error";
    case QXmppMessage::Normal:
        return "normal";
    case QXmppMessage::Chat:
        return "chat";
    case QXmppMessage::GroupChat:
        return "groupchat";
    case QXmppMessage::Headline:
        return "headline";
    default:
        qWarning("QXmppMessage::getTypeStr() invalid type %d", (int)getType());
        return "";
    }
}

void QXmppMessage::setType(QXmppMessage::Type type)
{
    m_type = type;
}

void QXmppMessage::setTypeFromStr(const QString& str)
{
    if(str == "error")
    {
        setType(QXmppMessage::Error);
        return;
    }
    else if(str == "")   // if no type is specified
    {
        setType(QXmppMessage::Normal);
        return;
    }
    else if(str == "normal")
    {
        setType(QXmppMessage::Normal);
        return;
    }
    else if(str == "chat")
    {
        setType(QXmppMessage::Chat);
        return;
    }
    else if(str == "groupchat")
    {
        setType(QXmppMessage::GroupChat);
        return;
    }
    else if(str == "headline")
    {
        setType(QXmppMessage::Headline);
        return;
    }
    else
    {
        setType(static_cast<QXmppMessage::Type>(-1));
        qWarning("QXmppMessage::setTypeFromStr() invalid input string type: %s",
                 qPrintable(str));
        return;
    }
}

QXmppMessage::State QXmppMessage::getState() const
{
    return m_state;
}

void QXmppMessage::setState(QXmppMessage::State state)
{
    m_state = state;
}

void QXmppMessage::parse(QDomElement &element)
{
    setFrom(element.attribute("from"));
    setTo(element.attribute("to"));
    setTypeFromStr(element.attribute("type"));
    setBody(unescapeString(
            element.firstChildElement("body").text()));
    setSubject(unescapeString(
            element.firstChildElement("subject").text()));
    setThread(element.firstChildElement("thread").text());

    QDomElement errorElement = element.
                               firstChildElement("error");
    if(!errorElement.isNull())
    {
        QXmppStanza::Error error = parseError(errorElement);
        setError(error);
    }

    for (int i = Active; i <= Paused; i++)
    {
        QDomElement stateElement = element.firstChildElement(chat_states[i]);
        if (!stateElement.isNull() &&
            stateElement.namespaceURI() == ns_chat_states)
        {
            m_state = static_cast<QXmppMessage::State>(i);
            break;
        }
    }

    QDomElement xElement = element.firstChildElement("x");
    if(!xElement.isNull())
        setExtensions(QXmppElement(xElement));
}

void QXmppMessage::toXml(QXmlStreamWriter *xmlWriter) const
{

    xmlWriter->writeStartElement("message");
    helperToXmlAddAttribute(xmlWriter, "xml:lang", getLang());
    helperToXmlAddAttribute(xmlWriter,  "id", getId());
    helperToXmlAddAttribute(xmlWriter, "to", getTo());
    helperToXmlAddAttribute(xmlWriter, "from", getFrom());
    helperToXmlAddAttribute(xmlWriter,  "type", getTypeStr());
    if (!m_subject.isEmpty())
        helperToXmlAddTextElement(xmlWriter, "subject", m_subject);
    if (!m_body.isEmpty())
        helperToXmlAddTextElement(xmlWriter, "body", m_body);
    if (!m_thread.isEmpty())
        helperToXmlAddTextElement(xmlWriter, "thread", m_thread);
    getError().toXml(xmlWriter);

    if (m_state > None && m_state <= Paused)
    {
        xmlWriter->writeStartElement(chat_states[m_state]);
        helperToXmlAddAttribute(xmlWriter, "xmlns", ns_chat_states);
        xmlWriter->writeEndElement();
    }

    foreach (const QXmppElement &extension, getExtensions())
        extension.toXml(xmlWriter);
    xmlWriter->writeEndElement();
}

QString QXmppMessage::getBody() const
{
    return m_body;
}

void QXmppMessage::setBody(const QString& body)
{
    m_body = body;
}

QString QXmppMessage::getSubject() const
{
    return m_subject;
}

void QXmppMessage::setSubject(const QString& sub)
{
    m_subject = sub;
}

QString QXmppMessage::getThread() const
{
    return m_thread;
}

void QXmppMessage::setThread(const QString& thread)
{
    m_thread = thread;
}

<|endoftext|>