<commit_before>#ifndef MIMOSA_CONTAINER_INTRUSIVE_SLIST_HH
# define MIMOSA_CONTAINER_INTRUSIVE_SLIST_HH

# include <cassert>
# include <cstddef>

# include "../non-copyable.hh"

namespace mimosa
{
  namespace container
  {
    template <typename Ptr>
    class IntrusiveSlistHook
    {
    public:
      inline IntrusiveSlistHook() : next_(nullptr) {}
      inline IntrusiveSlistHook(const IntrusiveSlistHook<Ptr> &) : next_(nullptr) {}
      inline IntrusiveSlistHook<Ptr> & operator=(const IntrusiveSlistHook<Ptr> &) { return *this; }

      Ptr next_;
    };

    template <typename T, typename Ptr, IntrusiveSlistHook<Ptr> T::*Member>
    class IntrusiveSlist;

    template <typename T, typename Ptr, IntrusiveSlistHook<Ptr> T::*Member>
    class IntrusiveSlistIterator
    {
    public:
      inline IntrusiveSlistIterator(const IntrusiveSlist<T, Ptr, Member> & slist, Ptr item)
        : slist_(slist), item_(item)
      {
      }

      inline T & operator*() const { return *item_; }
      inline Ptr operator->() const { return item_; }
      inline IntrusiveSlistIterator<T, Ptr, Member> & operator++()
      {
        assert(item_);
        if ((item_->*Member).next_ == item_ ||
            item_ == slist_.tail_)
          item_ = nullptr;
        else
          item_ = (item_->*Member).next_;
        return *this;
      }

      inline bool operator==(const IntrusiveSlistIterator<T, Ptr, Member> & other) const
      {
        return &slist_ == &other.slist_ && item_ == other.item_;
      }

      inline bool operator!=(const IntrusiveSlistIterator<T, Ptr, Member> & other) const
      {
        return !(*this == other);
      }

    private:
      const IntrusiveSlist<T, Ptr, Member> & slist_;
      Ptr                                    item_;
    };

    template <typename T, typename Ptr, IntrusiveSlistHook<Ptr> T::*Member>
    class IntrusiveSlist : private NonCopyable
    {
    public:
      typedef IntrusiveSlistIterator<T, Ptr, Member> iterator;
      friend class IntrusiveSlistIterator<T, Ptr, Member>;

      inline IntrusiveSlist() : tail_(nullptr), size_(0) {}
      inline ~IntrusiveSlist()
      {
        while (!empty())
          pop();
      }

      inline bool empty() const
      {
        return !tail_;
      }

      inline size_t size() const
      {
        return size_;
      }

      inline void push(T & item)
      {
        ++size_;
        if (!tail_)
          (item.*Member).next_ = &item;
        else
        {
          (item.*Member).next_   = (tail_->*Member).next_;
          (tail_->*Member).next_ = &item;
        }
        tail_ = &item;
      }

      inline T & front() const
      {
        assert(tail_);
        return *(tail_->*Member).next_;
      }

      inline T & back() const
      {
        assert(tail_);
        return *tail_;
      }

      inline void pop()
      {
        if (!tail_)
          return;
        --size_;
        if (tail_ == (tail_->*Member).next_)
        {
          (tail_->*Member).next_ = nullptr;
          tail_ = nullptr;
        }
        else
        {
          Ptr tmp                = (tail_->*Member).next_;
          (tail_->*Member).next_ = (tmp->*Member).next_;
          (tmp->*Member).next_   = nullptr;
        }
      }

      inline void clear()
      {
        // poping everything to unlink (and potentially release while unref)
        while (!empty())
          pop();
      }

      iterator begin() const { return empty() ? end() : iterator(*this, (tail_->*Member).next_); }
      iterator end() const { return iterator(*this, nullptr); }

    private:
      Ptr    tail_;
      size_t size_;
    };
  }
}

#endif /* !MIMOSA_CONTAINER_INTRUSIVE_SLIST_HH */
<commit_msg>intrusive-slist now expose ptr instead of ref.<commit_after>#ifndef MIMOSA_CONTAINER_INTRUSIVE_SLIST_HH
# define MIMOSA_CONTAINER_INTRUSIVE_SLIST_HH

# include <cassert>
# include <cstddef>

# include "../non-copyable.hh"

namespace mimosa
{
  namespace container
  {
    template <typename Ptr>
    class IntrusiveSlistHook
    {
    public:
      inline IntrusiveSlistHook() : next_(nullptr) {}
      inline IntrusiveSlistHook(const IntrusiveSlistHook<Ptr> &) : next_(nullptr) {}
      inline IntrusiveSlistHook<Ptr> & operator=(const IntrusiveSlistHook<Ptr> &) { return *this; }

      Ptr next_;
    };

    template <typename T, typename Ptr, IntrusiveSlistHook<Ptr> T::*Member>
    class IntrusiveSlist;

    template <typename T, typename Ptr, IntrusiveSlistHook<Ptr> T::*Member>
    class IntrusiveSlistIterator
    {
    public:
      inline IntrusiveSlistIterator(const IntrusiveSlist<T, Ptr, Member> & slist, Ptr item)
        : slist_(slist), item_(item)
      {
      }

      inline T & operator*() const { return *item_; }
      inline Ptr operator->() const { return item_; }
      inline IntrusiveSlistIterator<T, Ptr, Member> & operator++()
      {
        assert(item_);
        if ((item_->*Member).next_ == item_ ||
            item_ == slist_.tail_)
          item_ = nullptr;
        else
          item_ = (item_->*Member).next_;
        return *this;
      }

      inline bool operator==(const IntrusiveSlistIterator<T, Ptr, Member> & other) const
      {
        return &slist_ == &other.slist_ && item_ == other.item_;
      }

      inline bool operator!=(const IntrusiveSlistIterator<T, Ptr, Member> & other) const
      {
        return !(*this == other);
      }

    private:
      const IntrusiveSlist<T, Ptr, Member> & slist_;
      Ptr                                    item_;
    };

    template <typename T, typename Ptr, IntrusiveSlistHook<Ptr> T::*Member>
    class IntrusiveSlist : private NonCopyable
    {
    public:
      typedef IntrusiveSlistIterator<T, Ptr, Member> iterator;
      friend class IntrusiveSlistIterator<T, Ptr, Member>;

      inline IntrusiveSlist() : tail_(nullptr), size_(0) {}
      inline ~IntrusiveSlist()
      {
        while (!empty())
          pop();
      }

      inline bool empty() const
      {
        return !tail_;
      }

      inline size_t size() const
      {
        return size_;
      }

      inline void push(Ptr item)
      {
        ++size_;
        if (!tail_)
          (item->*Member).next_ = item;
        else
        {
          (item->*Member).next_  = (tail_->*Member).next_;
          (tail_->*Member).next_ = item;
        }
        tail_ = item;
      }

      inline Ptr front() const
      {
        assert(tail_);
        return (tail_->*Member).next_;
      }

      inline Ptr back() const
      {
        assert(tail_);
        return tail_;
      }

      inline void pop()
      {
        if (!tail_)
          return;
        --size_;
        if (tail_ == (tail_->*Member).next_)
        {
          (tail_->*Member).next_ = nullptr;
          tail_ = nullptr;
        }
        else
        {
          Ptr tmp                = (tail_->*Member).next_;
          (tail_->*Member).next_ = (tmp->*Member).next_;
          (tmp->*Member).next_   = nullptr;
        }
      }

      inline void clear()
      {
        // poping everything to unlink (and potentially release while unref)
        while (!empty())
          pop();
      }

      iterator begin() const { return empty() ? end() : iterator(*this, (tail_->*Member).next_); }
      iterator end() const { return iterator(*this, nullptr); }

    private:
      Ptr    tail_;
      size_t size_;
    };
  }
}

#endif /* !MIMOSA_CONTAINER_INTRUSIVE_SLIST_HH */
<|endoftext|>


<commit_before>

// Copyright 2010-2012 University of Washington. All Rights Reserved.
// LICENSE_PLACEHOLDER
// This software was created with Government support under DE
// AC05-76RL01830 awarded by the United States Department of
// Energy. The Government has certain rights in the software.

#ifndef __FULLEMPTY_HPP__
#define __FULLEMPTY_HPP__

#include <gflags/gflags.h>
#include <glog/logging.h>

#include "ConditionVariable.hpp"

namespace Grappa {

  /// @addtogroup Synchronization
  /// @{

  /// Wrapper class to provide full-bit semantics for arbitrary data.
  template< typename T >
  class FullEmpty {
  private:
    enum class State : bool { EMPTY = false, FULL = true };

    union {
      struct {
	State state_ : 1;
	intptr_t waiters_ : 63; // can't include pointers in bitfield, so use intptr_t
      };
      intptr_t raw_; // unnecessary; just to ensure alignment
    };

    T t_;

    void block_until( State desired_state ) {
      while( state_ != desired_state ) {
	Grappa::wait( this );
      }
    }

  public:
    FullEmpty( ) : state_( State::EMPTY ), waiters_( 0 ), t_() {}

    inline bool full() { return state_ == State::FULL; }

    T writeXF( T t ) {
      t_ = t;
      state_ = State::FULL;
      Grappa::broadcast( this );
      return t_;
    }

    T writeEF( T t ) {
      block_until(State::EMPTY);
      return writeXF( t );
    }

    T writeFF( T t ) {
      block_until(State::FULL);
      return writeXF( t );
    }

    T readXX() {
      return t_;
    }

    T readFF() {
      block_until(State::FULL);
      return readXX();
    }

    T readFE() {
      block_until(State::FULL);
      state_ = State::EMPTY;
      Grappa::broadcast( this );
      return readXX();
    }

  };
  /// @}

}

#endif
<commit_msg>Add a full constructor to FullEmpty<commit_after>

// Copyright 2010-2012 University of Washington. All Rights Reserved.
// LICENSE_PLACEHOLDER
// This software was created with Government support under DE
// AC05-76RL01830 awarded by the United States Department of
// Energy. The Government has certain rights in the software.

#ifndef __FULLEMPTY_HPP__
#define __FULLEMPTY_HPP__

#include <gflags/gflags.h>
#include <glog/logging.h>

#include "ConditionVariable.hpp"

namespace Grappa {

  /// @addtogroup Synchronization
  /// @{

  /// Wrapper class to provide full-bit semantics for arbitrary data.
  template< typename T >
  class FullEmpty {
  private:
    enum class State : bool { EMPTY = false, FULL = true };

    union {
      struct {
	State state_ : 1;
	intptr_t waiters_ : 63; // can't include pointers in bitfield, so use intptr_t
      };
      intptr_t raw_; // unnecessary; just to ensure alignment
    };

    T t_;

    void block_until( State desired_state ) {
      while( state_ != desired_state ) {
	Grappa::wait( this );
      }
    }

  public:
    FullEmpty( ) : state_( State::EMPTY ), waiters_( 0 ), t_() {}

    FullEmpty( T t ) : state_( State::FULL ), waiters_( 0 ), t_(t) {}

    inline bool full() { return state_ == State::FULL; }

    T writeXF( T t ) {
      t_ = t;
      state_ = State::FULL;
      Grappa::broadcast( this );
      return t_;
    }

    T writeEF( T t ) {
      block_until(State::EMPTY);
      return writeXF( t );
    }

    T writeFF( T t ) {
      block_until(State::FULL);
      return writeXF( t );
    }

    T readXX() {
      return t_;
    }

    T readFF() {
      block_until(State::FULL);
      return readXX();
    }

    T readFE() {
      block_until(State::FULL);
      state_ = State::EMPTY;
      Grappa::broadcast( this );
      return readXX();
    }

  };
  /// @}

}

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLTextListBlockContext.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 16:09:53 $
 *
 *  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 _XMLTEXTLISTBLOCKCONTEXT_HXX
#define _XMLTEXTLISTBLOCKCONTEXT_HXX

#ifndef _COM_SUN_STAR_CONTAINER_XINDEXREPLACE_HPP_
#include <com/sun/star/container/XIndexReplace.hpp>
#endif

#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif

class XMLTextImportHelper;

class XMLTextListBlockContext : public SvXMLImportContext
{
    XMLTextImportHelper&    rTxtImport;

    ::com::sun::star::uno::Reference<
                ::com::sun::star::container::XIndexReplace > xNumRules;

    const ::rtl::OUString   sNumberingRules;
    ::rtl::OUString         sStyleName;
    SvXMLImportContextRef   xParentListBlock;
    sal_Int16               nLevel;
    sal_Int32               nLevels;
    sal_Bool                bRestartNumbering : 1;
    sal_Bool                bSetDefaults : 1;

public:

    TYPEINFO();

    XMLTextListBlockContext( SvXMLImport& rImport,
            XMLTextImportHelper& rTxtImp, sal_uInt16 nPrfx,
                const ::rtl::OUString& rLName,
                   const ::com::sun::star::uno::Reference<
                    ::com::sun::star::xml::sax::XAttributeList > & xAttrList );
    virtual ~XMLTextListBlockContext();

    virtual void EndElement();

    SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix,
                const ::rtl::OUString& rLocalName,
                 const ::com::sun::star::uno::Reference<
                    ::com::sun::star::xml::sax::XAttributeList > & xAttrList );

    const ::rtl::OUString& GetStyleName() const { return sStyleName; }
    sal_Int16 GetLevel() const { return nLevel; }
    sal_Bool IsRestartNumbering() const { return bRestartNumbering; }
    void ResetRestartNumbering() { bRestartNumbering = sal_False; }

//  sal_Bool HasGeneratedStyle() const { return xGenNumRule.is(); }
    const ::com::sun::star::uno::Reference <
        ::com::sun::star::container::XIndexReplace >& GetNumRules() const
        { return xNumRules; }
};

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.6.162); FILE MERGED 2008/04/01 13:05:31 thb 1.6.162.2: #i85898# Stripping all external header guards 2008/03/31 16:28:37 rt 1.6.162.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: XMLTextListBlockContext.hxx,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.
 *
 ************************************************************************/

#ifndef _XMLTEXTLISTBLOCKCONTEXT_HXX
#define _XMLTEXTLISTBLOCKCONTEXT_HXX

#include <com/sun/star/container/XIndexReplace.hpp>
#include <xmloff/xmlictxt.hxx>

class XMLTextImportHelper;

class XMLTextListBlockContext : public SvXMLImportContext
{
    XMLTextImportHelper&    rTxtImport;

    ::com::sun::star::uno::Reference<
                ::com::sun::star::container::XIndexReplace > xNumRules;

    const ::rtl::OUString   sNumberingRules;
    ::rtl::OUString         sStyleName;
    SvXMLImportContextRef   xParentListBlock;
    sal_Int16               nLevel;
    sal_Int32               nLevels;
    sal_Bool                bRestartNumbering : 1;
    sal_Bool                bSetDefaults : 1;

public:

    TYPEINFO();

    XMLTextListBlockContext( SvXMLImport& rImport,
            XMLTextImportHelper& rTxtImp, sal_uInt16 nPrfx,
                const ::rtl::OUString& rLName,
                   const ::com::sun::star::uno::Reference<
                    ::com::sun::star::xml::sax::XAttributeList > & xAttrList );
    virtual ~XMLTextListBlockContext();

    virtual void EndElement();

    SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix,
                const ::rtl::OUString& rLocalName,
                 const ::com::sun::star::uno::Reference<
                    ::com::sun::star::xml::sax::XAttributeList > & xAttrList );

    const ::rtl::OUString& GetStyleName() const { return sStyleName; }
    sal_Int16 GetLevel() const { return nLevel; }
    sal_Bool IsRestartNumbering() const { return bRestartNumbering; }
    void ResetRestartNumbering() { bRestartNumbering = sal_False; }

//  sal_Bool HasGeneratedStyle() const { return xGenNumRule.is(); }
    const ::com::sun::star::uno::Reference <
        ::com::sun::star::container::XIndexReplace >& GetNumRules() const
        { return xNumRules; }
};

#endif
<|endoftext|>


<commit_before>/*##############################################################################

    Copyright (C) 2011 HPCC Systems.

    All rights reserved. This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
############################################################################## */

#ifndef _JSCM_HPP_
#define _JSCM_HPP_

#undef interface
#define implements   public
#define extends      public

#ifdef _MSC_VER
#define interface    struct __declspec(novtable)
#else
#define interface    struct
#endif

interface IInterface
{
    virtual void Link() const = 0;
    virtual bool Release() const = 0;
};

template <class X> inline void Link(X * ptr)    { if (ptr) ptr->Link(); }
template <class X> inline void Release(X * ptr) { if (ptr) ptr->Release(); }

#define QUERYINTERFACE(ptr, TYPE)   (dynamic_cast<TYPE *>(ptr))

//This base class implements a shared pointer based on a link count held in the object.
//The two derived classes Owned and Linked should be used as the concrete types to construct a shared object
//from a pointer.
template <class CLASS> class Shared
{
public:
    inline Shared()                              { ptr = NULL; }
    inline Shared(CLASS * _ptr, bool owned)      { ptr = _ptr; if (!owned && _ptr) _ptr->Link(); }
    inline Shared(const Shared<CLASS> & other)   { ptr = other.getLink(); }
    inline ~Shared()                             { ::Release(ptr); }

    inline Shared<CLASS> & operator = (const Shared<CLASS> & other) { set(other.get()); return *this;  }

    inline CLASS * operator -> () const         { return ptr; }
    inline operator CLASS *() const             { return ptr; }

    inline void clear()                         { CLASS *temp=ptr; ptr=NULL; ::Release(temp); }
    inline CLASS * get() const                  { return ptr; }
    inline CLASS * getClear()                   { CLASS * temp = ptr; ptr = NULL; return temp; }
    inline CLASS * getLink() const              { if (ptr) ptr->Link(); return ptr; }
    inline void set(CLASS * _ptr)
    {
        CLASS * temp = ptr;
        if (temp != _ptr)
        {
            ::Link(_ptr);
            ptr = _ptr;
            ::Release(temp);
        }
    }
    inline void set(const Shared<CLASS> &other) { set(other.get()); }
    inline void setown(CLASS * _ptr)            { CLASS * temp = ptr; ptr = _ptr; ::Release(temp); }

protected:
    inline Shared(CLASS * _ptr)                  { ptr = _ptr; } // deliberately protected

private:
    inline void setown(const Shared<CLASS> &other); // illegal - going to cause a -ve leak
    inline Shared<CLASS> & operator = (const CLASS * other);

private:
    CLASS * ptr;
};

//An Owned Shared object takes ownership of the pointer that is passed in the constructor.
template <class CLASS> class Owned : public Shared<CLASS>
{
public:
    inline Owned()                              { }
    inline Owned(CLASS * _ptr) : Shared<CLASS>(_ptr)   { }

    inline Shared<CLASS> & operator = (const Shared<CLASS> & other) { set(other.get()); return *this;  }

private:
    inline Owned(const Shared<CLASS> & other); // Almost certainly a bug
    inline Owned<CLASS> & operator = (const CLASS * other);
};

//A Linked Shared object takes does not take ownership of the pointer that is passed in the constructor.
template <class CLASS> class Linked : public Shared<CLASS>
{
public:
    inline Linked()                         { }
    inline Linked(CLASS * _ptr) : Shared<CLASS>(LINK(_ptr)) { }
    inline Linked(const Shared<CLASS> & other) : Shared<CLASS>(other) { }

    inline Shared<CLASS> & operator = (const Shared<CLASS> & other) { set(other.get()); return *this;  }

private:
    inline Linked<CLASS> & operator = (const CLASS * other);
};

// IStringVal manages returning of arbitrary null-terminated string data between systems that may not share heap managers
interface IStringVal
{
    virtual const char * str() const = 0;
    virtual void set(const char * val) = 0;
    virtual void clear() = 0;
    virtual void setLen(const char * val, unsigned length) = 0;
    virtual unsigned length() const = 0;
};

// IDataVal manages returning of arbitrary unterminated binary data between systems that may not share heap managers
interface IDataVal
{
    virtual const void * data() const = 0;
    virtual void clear() = 0;
    virtual void setLen(const void * val, unsigned length) = 0;
    virtual unsigned length() const = 0;
    virtual void * reserve(unsigned length) = 0;
};

// IIterator
interface IIterator : extends IInterface
{
    virtual bool first() = 0;
    virtual bool next() = 0;
    virtual bool isValid() = 0;
    virtual IInterface & query() = 0;
    virtual IInterface & get() = 0;
};

template <class C>
interface IIteratorOf : public IInterface
{
public:
    virtual bool first() = 0;
    virtual bool next() = 0;
    virtual bool isValid() = 0;
    virtual C  & query() = 0;
            C  & get() { C &c = query(); c.Link(); return c; }
};

#define ForEach(i)              for((i).first();(i).isValid();(i).next())

typedef IInterface * IInterfacePtr;
typedef Owned<IInterface> OwnedIInterface;
typedef Linked<IInterface> LinkedIInterface;

template <class X> inline X * LINK(X * ptr)     { if (ptr) ptr->Link(); return ptr; }
template <class X> inline X & OLINK(X & obj)        { obj.Link(); return obj; }
template <class X> inline X * LINK(const Shared<X> &ptr) { return ptr.getLink(); }

#endif
<commit_msg>More changes need to avoid clang errors<commit_after>/*##############################################################################

    Copyright (C) 2011 HPCC Systems.

    All rights reserved. This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
############################################################################## */

#ifndef _JSCM_HPP_
#define _JSCM_HPP_

#undef interface
#define implements   public
#define extends      public

#ifdef _MSC_VER
#define interface    struct __declspec(novtable)
#else
#define interface    struct
#endif

interface IInterface
{
    virtual void Link() const = 0;
    virtual bool Release() const = 0;
};

template <class X> inline void Link(X * ptr)    { if (ptr) ptr->Link(); }
template <class X> inline void Release(X * ptr) { if (ptr) ptr->Release(); }

#define QUERYINTERFACE(ptr, TYPE)   (dynamic_cast<TYPE *>(ptr))

//This base class implements a shared pointer based on a link count held in the object.
//The two derived classes Owned and Linked should be used as the concrete types to construct a shared object
//from a pointer.
template <class CLASS> class Shared
{
public:
    inline Shared()                              { ptr = NULL; }
    inline Shared(CLASS * _ptr, bool owned)      { ptr = _ptr; if (!owned && _ptr) _ptr->Link(); }
    inline Shared(const Shared<CLASS> & other)   { ptr = other.getLink(); }
    inline ~Shared()                             { ::Release(ptr); }

    inline Shared<CLASS> & operator = (const Shared<CLASS> & other) { this->set(other.get()); return *this;  }

    inline CLASS * operator -> () const         { return ptr; }
    inline operator CLASS *() const             { return ptr; }

    inline void clear()                         { CLASS *temp=ptr; ptr=NULL; ::Release(temp); }
    inline CLASS * get() const                  { return ptr; }
    inline CLASS * getClear()                   { CLASS * temp = ptr; ptr = NULL; return temp; }
    inline CLASS * getLink() const              { if (ptr) ptr->Link(); return ptr; }
    inline void set(CLASS * _ptr)
    {
        CLASS * temp = ptr;
        if (temp != _ptr)
        {
            ::Link(_ptr);
            ptr = _ptr;
            ::Release(temp);
        }
    }
    inline void set(const Shared<CLASS> &other) { this->set(other.get()); }
    inline void setown(CLASS * _ptr)            { CLASS * temp = ptr; ptr = _ptr; ::Release(temp); }

protected:
    inline Shared(CLASS * _ptr)                  { ptr = _ptr; } // deliberately protected

private:
    inline void setown(const Shared<CLASS> &other); // illegal - going to cause a -ve leak
    inline Shared<CLASS> & operator = (const CLASS * other);

private:
    CLASS * ptr;
};

//An Owned Shared object takes ownership of the pointer that is passed in the constructor.
template <class CLASS> class Owned : public Shared<CLASS>
{
public:
    inline Owned()                              { }
    inline Owned(CLASS * _ptr) : Shared<CLASS>(_ptr)   { }

    inline Shared<CLASS> & operator = (const Shared<CLASS> & other) { this->set(other.get()); return *this;  }

private:
    inline Owned(const Shared<CLASS> & other); // Almost certainly a bug
    inline Owned<CLASS> & operator = (const CLASS * other);
};

//A Linked Shared object takes does not take ownership of the pointer that is passed in the constructor.
template <class CLASS> class Linked : public Shared<CLASS>
{
public:
    inline Linked()                         { }
    inline Linked(CLASS * _ptr) : Shared<CLASS>(LINK(_ptr)) { }
    inline Linked(const Shared<CLASS> & other) : Shared<CLASS>(other) { }

    inline Shared<CLASS> & operator = (const Shared<CLASS> & other) { this->set(other.get()); return *this;  }

private:
    inline Linked<CLASS> & operator = (const CLASS * other);
};

// IStringVal manages returning of arbitrary null-terminated string data between systems that may not share heap managers
interface IStringVal
{
    virtual const char * str() const = 0;
    virtual void set(const char * val) = 0;
    virtual void clear() = 0;
    virtual void setLen(const char * val, unsigned length) = 0;
    virtual unsigned length() const = 0;
};

// IDataVal manages returning of arbitrary unterminated binary data between systems that may not share heap managers
interface IDataVal
{
    virtual const void * data() const = 0;
    virtual void clear() = 0;
    virtual void setLen(const void * val, unsigned length) = 0;
    virtual unsigned length() const = 0;
    virtual void * reserve(unsigned length) = 0;
};

// IIterator
interface IIterator : extends IInterface
{
    virtual bool first() = 0;
    virtual bool next() = 0;
    virtual bool isValid() = 0;
    virtual IInterface & query() = 0;
    virtual IInterface & get() = 0;
};

template <class C>
interface IIteratorOf : public IInterface
{
public:
    virtual bool first() = 0;
    virtual bool next() = 0;
    virtual bool isValid() = 0;
    virtual C  & query() = 0;
            C  & get() { C &c = query(); c.Link(); return c; }
};

#define ForEach(i)              for((i).first();(i).isValid();(i).next())

typedef IInterface * IInterfacePtr;
typedef Owned<IInterface> OwnedIInterface;
typedef Linked<IInterface> LinkedIInterface;

template <class X> inline X * LINK(X * ptr)     { if (ptr) ptr->Link(); return ptr; }
template <class X> inline X & OLINK(X & obj)        { obj.Link(); return obj; }
template <class X> inline X * LINK(const Shared<X> &ptr) { return ptr.getLink(); }

#endif
<|endoftext|>


<commit_before>/******************************************************************************
 * c7a/core/hash_table.hpp
 *
 * Hash table with support for reduce and partitions.
 *
 * Part of Project c7a.
 *
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#pragma once

#include <map>
#include <iostream>
#include <c7a/common/logger.hpp>
#include <string>
#include <vector>
#include <stdexcept>
#include <array>

#include "c7a/api/function_traits.hpp"
#include "c7a/data/data_manager.hpp"

namespace c7a {
namespace core {
template <typename KeyExtractor, typename ReduceFunction, typename EmitterFunction>
class ReducePostTable
{
    static const bool debug = false;

    using key_t = typename FunctionTraits<KeyExtractor>::result_type;

    using value_t = typename FunctionTraits<ReduceFunction>::result_type;

protected:
    template <typename key_t, typename value_t>
    struct node {
        key_t   key;
        value_t value;
        node    * next;
    };

public:
    ReducePostTable(size_t num_buckets, size_t num_buckets_resize_scale,
                    size_t max_num_items_per_bucket, size_t max_num_items_table,
                    KeyExtractor key_extractor, ReduceFunction reduce_function,
                    std::vector<EmitterFunction> emit)
        : num_buckets_init_scale_(num_buckets),
          num_buckets_resize_scale_(num_buckets_resize_scale),
          max_num_items_per_bucket_(max_num_items_per_bucket),
          max_num_items_table_(max_num_items_table),
          key_extractor_(key_extractor),
          reduce_function_(reduce_function),
          emit_(emit)
    {
        init();
    }

    // TODO(ms): the BlockEmitter must be a plain template like KeyExtractor.
    ReducePostTable(KeyExtractor key_extractor,
                    ReduceFunction reduce_function, std::vector<EmitterFunction> emit)
        : key_extractor_(key_extractor),
          reduce_function_(reduce_function),
          emit_(emit)
    {
        init();
    }

    ~ReducePostTable() { }

    void init()
    {
        num_buckets_ = num_buckets_init_scale_;
        vector_.resize(num_buckets_, nullptr);
    }

    /*!
     * Inserts a key/value pair.
     *
     * Optionally, this may be reduce using the reduce function
     * in case the key already exists.
     */
    void Insert(const value_t& p)
    {
        key_t key = key_extractor_(p);

        size_t hashed_key = std::hash<key_t>() (key) % num_buckets_;

        LOG << "key: "
            << key
            << " to idx: "
            << hashed_key;

        // TODO(ms): the first nullptr case is identical. remove and use null as
        // sentinel.

        // bucket is empty
        if (vector_[hashed_key] == nullptr) {
            LOG << "bucket empty, inserting...";

            node<key_t, value_t>* n = new node<key_t, value_t>;
            n->key = key;
            n->value = p;
            n->next = nullptr;
            vector_[hashed_key] = n;

            // increase total counter
            table_size_++;
        }
        else {
            LOG << "bucket not empty, checking if key already exists...";

            // check if item with same key
            node<key_t, value_t>* curr_node = vector_[hashed_key];
            do {
                if (key == curr_node->key) {
                    LOG << "match of key: "
                        << key
                        << " and "
                        << curr_node->key
                        << " ... reducing...";

                    (*curr_node).value = reduce_function_(curr_node->value, p);

                    LOG << "...finished reduce!";

                    break;
                }

                curr_node = curr_node->next;
            } while (curr_node != nullptr);

            // no item found with key
            if (curr_node == nullptr) {
                LOG << "key doesn't exist in baguette, appending...";

                // insert at first pos
                node<key_t, value_t>* n = new node<key_t, value_t>;
                n->key = key;
                n->value = p;
                n->next = vector_[hashed_key];
                vector_[hashed_key] = n;

                // increase total counter
                table_size_++;

                LOG << "key appended, metrics updated!";
            }
        }

        if (table_size_ > max_num_items_table_) {
            throw std::invalid_argument("Hashtable overflown. No external memory functionality implemented yet");
        }
    }

    /*!
     * Emits element to all childs
     */
    void EmitAll(value_t& element)
    {
        for (auto emitter : emit_) {
            emitter(element);
        }
    }
    /*!
     * Flushes all items.
     */
    void Flush()
    {
        LOG << "Flushing in progress";

        // retrieve items
        for (size_t i = 0; i < num_buckets_; i++) {
            if (vector_[i] != nullptr) {
                node<key_t, value_t>* curr_node = vector_[i];
                do {
                    EmitAll(curr_node->value);
                    curr_node = curr_node->next;
                } while (curr_node != nullptr);
                vector_[i] = nullptr;
            }
        }

        // reset counters
        table_size_ = 0;
    }

    /*!
     * Returns the total num of items.
     */
    size_t Size()
    {
        return table_size_;
    }

    /*!
     * Returns the total num of buckets.
     */
    size_t NumBuckets()
    {
        return num_buckets_;
    }

    /*!
     * Sets the maximum size of the hash table. We don't want to push 2vt elements before flush happens.
     */
    void SetMaxSize(size_t size)
    {
        max_num_items_table_ = size;
    }

    /*!
     * Resizes the table by increasing the number of buckets using some
     * resize scale factor. All items are rehashed as part of the operation
     */
    void ResizeUp()
    {
        LOG << "Resizing";
        num_buckets_ *= num_buckets_resize_scale_;
        // init new array
        std::vector<node<key_t, value_t>*> vector_old = vector_;
        std::vector<node<key_t, value_t>*> vector_new;
        vector_new.resize(num_buckets_, nullptr);
        vector_ = vector_new;
        // rehash all items in old array
        for (auto bucket : vector_old) {
            Insert(bucket);
        }
        LOG << "Resized";
    }

    /*!
     * Removes all items in the table, but NOT flushing them.
     */
    void Clear()
    {
        LOG << "Clearing";
        std::fill(vector_.begin(), vector_.end(), nullptr);
        table_size_ = 0;
        LOG << "Cleared";
    }

    /*!
     * Removes all items in the table, but NOT flushing them.
     */
    void Reset()
    {
        LOG << "Resetting";
        num_buckets_ = num_buckets_init_scale_;
        vector_.resize(num_buckets_, nullptr);
        table_size_ = 0;
        LOG << "Resetted";
    }

    // prints content of hash table
    void Print()
    {
        for (int i = 0; i < num_buckets_; i++) {
            if (vector_[i] == nullptr) {
                LOG << "bucket "
                    << i
                    << " empty";
            }
            else {
                std::string log = "";

                // check if item with same key
                node<key_t, value_t>* curr_node = vector_[i];
                value_t curr_item;
                do {
                    curr_item = curr_node->value;

                    log += "(";
                    log += curr_item.second;
                    log += ") ";

                    curr_node = curr_node->next;
                } while (curr_node != nullptr);

                LOG << "bucket "
                    << i
                    << ": "
                    << log;
            }
        }

        return;
    }

private:
    size_t num_buckets_;                    // num buckets

    size_t num_buckets_init_scale_ = 65536; // set number of buckets per partition based on num_partitions
    // multiplied with some scaling factor, must be equal to or greater than 1

    size_t num_buckets_resize_scale_ = 2;   // resize scale on max_num_items_per_bucket_

    size_t max_num_items_per_bucket_ = 256; // max num of items per bucket before resize

    size_t table_size_ = 0;                 // total number of items

    size_t max_num_items_table_ = 1048576;  // max num of items before spilling of largest partition

    KeyExtractor key_extractor_;

    ReduceFunction reduce_function_;

    std::vector<EmitterFunction> emit_;

    std::vector<node<key_t, value_t>*> vector_;
};
}
}

/******************************************************************************/
<commit_msg>comment logging which was not working<commit_after>/******************************************************************************
 * c7a/core/hash_table.hpp
 *
 * Hash table with support for reduce and partitions.
 *
 * Part of Project c7a.
 *
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#pragma once

#include <map>
#include <iostream>
#include <c7a/common/logger.hpp>
#include <string>
#include <vector>
#include <stdexcept>
#include <array>

#include "c7a/api/function_traits.hpp"
#include "c7a/data/data_manager.hpp"

namespace c7a {
namespace core {
template <typename KeyExtractor, typename ReduceFunction, typename EmitterFunction>
class ReducePostTable
{
    static const bool debug = false;

    using key_t = typename FunctionTraits<KeyExtractor>::result_type;

    using value_t = typename FunctionTraits<ReduceFunction>::result_type;

protected:
    template <typename key_t, typename value_t>
    struct node {
        key_t   key;
        value_t value;
        node    * next;
    };

public:
    ReducePostTable(size_t num_buckets, size_t num_buckets_resize_scale,
                    size_t max_num_items_per_bucket, size_t max_num_items_table,
                    KeyExtractor key_extractor, ReduceFunction reduce_function,
                    std::vector<EmitterFunction> emit)
        : num_buckets_init_scale_(num_buckets),
          num_buckets_resize_scale_(num_buckets_resize_scale),
          max_num_items_per_bucket_(max_num_items_per_bucket),
          max_num_items_table_(max_num_items_table),
          key_extractor_(key_extractor),
          reduce_function_(reduce_function),
          emit_(emit)
    {
        init();
    }

    // TODO(ms): the BlockEmitter must be a plain template like KeyExtractor.
    ReducePostTable(KeyExtractor key_extractor,
                    ReduceFunction reduce_function, std::vector<EmitterFunction> emit)
        : key_extractor_(key_extractor),
          reduce_function_(reduce_function),
          emit_(emit)
    {
        init();
    }

    ~ReducePostTable() { }

    void init()
    {
        num_buckets_ = num_buckets_init_scale_;
        vector_.resize(num_buckets_, nullptr);
    }

    /*!
     * Inserts a key/value pair.
     *
     * Optionally, this may be reduce using the reduce function
     * in case the key already exists.
     */
    void Insert(const value_t& p)
    {
        key_t key = key_extractor_(p);

        size_t hashed_key = std::hash<key_t>() (key) % num_buckets_;

        LOG << "key: "
            << key
            << " to idx: "
            << hashed_key;

        // TODO(ms): the first nullptr case is identical. remove and use null as
        // sentinel.

        // bucket is empty
        if (vector_[hashed_key] == nullptr) {
            LOG << "bucket empty, inserting...";

            node<key_t, value_t>* n = new node<key_t, value_t>;
            n->key = key;
            n->value = p;
            n->next = nullptr;
            vector_[hashed_key] = n;

            // increase total counter
            table_size_++;
        }
        else {
            LOG << "bucket not empty, checking if key already exists...";

            // check if item with same key
            node<key_t, value_t>* curr_node = vector_[hashed_key];
            do {
                if (key == curr_node->key) {
                    LOG << "match of key: "
                        << key
                        << " and "
                        << curr_node->key
                        << " ... reducing...";

                    (*curr_node).value = reduce_function_(curr_node->value, p);

                    LOG << "...finished reduce!";

                    break;
                }

                curr_node = curr_node->next;
            } while (curr_node != nullptr);

            // no item found with key
            if (curr_node == nullptr) {
                LOG << "key doesn't exist in baguette, appending...";

                // insert at first pos
                node<key_t, value_t>* n = new node<key_t, value_t>;
                n->key = key;
                n->value = p;
                n->next = vector_[hashed_key];
                vector_[hashed_key] = n;

                // increase total counter
                table_size_++;

                LOG << "key appended, metrics updated!";
            }
        }

        if (table_size_ > max_num_items_table_) {
            throw std::invalid_argument("Hashtable overflown. No external memory functionality implemented yet");
        }
    }

    /*!
     * Emits element to all childs
     */
    void EmitAll(value_t& element)
    {
        for (auto emitter : emit_) {
            emitter(element);
        }
    }
    /*!
     * Flushes all items.
     */
    void Flush()
    {
        LOG << "Flushing in progress";

        // retrieve items
        for (size_t i = 0; i < num_buckets_; i++) {
            if (vector_[i] != nullptr) {
                node<key_t, value_t>* curr_node = vector_[i];
                do {
                    EmitAll(curr_node->value);
                    curr_node = curr_node->next;
                } while (curr_node != nullptr);
                vector_[i] = nullptr;
            }
        }

        // reset counters
        table_size_ = 0;
    }

    /*!
     * Returns the total num of items.
     */
    size_t Size()
    {
        return table_size_;
    }

    /*!
     * Returns the total num of buckets.
     */
    size_t NumBuckets()
    {
        return num_buckets_;
    }

    /*!
     * Sets the maximum size of the hash table. We don't want to push 2vt elements before flush happens.
     */
    void SetMaxSize(size_t size)
    {
        max_num_items_table_ = size;
    }

    /*!
     * Resizes the table by increasing the number of buckets using some
     * resize scale factor. All items are rehashed as part of the operation
     */
    void ResizeUp()
    {
        LOG << "Resizing";
        num_buckets_ *= num_buckets_resize_scale_;
        // init new array
        std::vector<node<key_t, value_t>*> vector_old = vector_;
        std::vector<node<key_t, value_t>*> vector_new;
        vector_new.resize(num_buckets_, nullptr);
        vector_ = vector_new;
        // rehash all items in old array
        for (auto bucket : vector_old) {
            Insert(bucket);
        }
        LOG << "Resized";
    }

    /*!
     * Removes all items in the table, but NOT flushing them.
     */
    void Clear()
    {
        LOG << "Clearing";
        std::fill(vector_.begin(), vector_.end(), nullptr);
        table_size_ = 0;
        LOG << "Cleared";
    }

    /*!
     * Removes all items in the table, but NOT flushing them.
     */
    void Reset()
    {
        LOG << "Resetting";
        num_buckets_ = num_buckets_init_scale_;
        vector_.resize(num_buckets_, nullptr);
        table_size_ = 0;
        LOG << "Resetted";
    }

    // prints content of hash table
    void Print()
    {
        for (int i = 0; i < num_buckets_; i++) {
            if (vector_[i] == nullptr) {
                LOG << "bucket "
                    << i
                    << " empty";
            }
            else {
                std::string log = "";

                // check if item with same key
                node<key_t, value_t>* curr_node = vector_[i];
                value_t curr_item;
                do {
                    curr_item = curr_node->value;

                    log += "(";
                    //log += curr_item.second;
                    log += ") ";

                    curr_node = curr_node->next;
                } while (curr_node != nullptr);

                LOG << "bucket "
                    << i
                    << ": "
                    << log;
            }
        }

        return;
    }

private:
    size_t num_buckets_;                    // num buckets

    size_t num_buckets_init_scale_ = 65536; // set number of buckets per partition based on num_partitions
    // multiplied with some scaling factor, must be equal to or greater than 1

    size_t num_buckets_resize_scale_ = 2;   // resize scale on max_num_items_per_bucket_

    size_t max_num_items_per_bucket_ = 256; // max num of items per bucket before resize

    size_t table_size_ = 0;                 // total number of items

    size_t max_num_items_table_ = 1048576;  // max num of items before spilling of largest partition

    KeyExtractor key_extractor_;

    ReduceFunction reduce_function_;

    std::vector<EmitterFunction> emit_;

    std::vector<node<key_t, value_t>*> vector_;
};
}
}

/******************************************************************************/
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * 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_xmlsecurity.hxx"

#include "resourcemanager.hxx"

#include <vcl/svapp.hxx>
#include <vcl/fixed.hxx>
#include <svtools/stdctrl.hxx>
#include <svl/solar.hrc>
#include <unotools/syslocale.hxx>
#include <rtl/ustring.h>
#include <rtl/ustrbuf.h>
#include <vector>

using ::rtl::OUString;
using namespace std;

namespace XmlSec
{
    static ResMgr*          pResMgr = 0;
    static SvtSysLocale*    pSysLocale = 0;

    ResMgr* GetResMgr( void )
    {
        if( !pResMgr )
        {
            ByteString  aName( "xmlsec" );
// MT: Change to Locale
            pResMgr = ResMgr::CreateResMgr( aName.GetBuffer() );
        }

    return pResMgr;
    }

    const LocaleDataWrapper&    GetLocaleData( void )
    {
        if (!pSysLocale)
            pSysLocale = new SvtSysLocale;
        return pSysLocale->GetLocaleData();
    }

    DateTime GetDateTime( const ::com::sun::star::util::DateTime& _rDT )
    {
        return DateTime(
            Date( _rDT.Day, _rDT.Month, _rDT.Year ),
            Time( _rDT.Hours, _rDT.Minutes, _rDT.Seconds, _rDT.HundredthSeconds ) );
    }

    String GetDateTimeString( const ::com::sun::star::util::DateTime& _rDT )
    {
        // String with date and time information (#i20172#)
        DateTime aDT( GetDateTime( _rDT ) );
        const LocaleDataWrapper& rLoDa = GetLocaleData();
        String sRet( rLoDa.getDate( aDT ) );
        sRet += ' ';
        sRet += rLoDa.getTime( aDT );
        return sRet;
    }

    String GetDateTimeString( const rtl::OUString& _rDate, const rtl::OUString& _rTime )
    {
        String sDay( _rDate, 6, 2 );
        String sMonth( _rDate, 4, 2 );
        String sYear( _rDate, 0, 4 );

        String sHour( _rTime, 0, 2 );
        String sMin( _rTime, 4, 2 );
        String sSec( _rTime, 6, 2 );

        Date aDate( (sal_uInt16)sDay.ToInt32(), (sal_uInt16) sMonth.ToInt32(), (sal_uInt16)sYear.ToInt32() );
        Time aTime( sHour.ToInt32(), sMin.ToInt32(), sSec.ToInt32(), 0 );
        const LocaleDataWrapper& rLoDa = GetLocaleData();
        String aStr( rLoDa.getDate( aDate ) );
        aStr.AppendAscii( " " );
        aStr += rLoDa.getTime( aTime );
        return aStr;
    }

    String GetDateString( const ::com::sun::star::util::DateTime& _rDT )
    {
        return GetLocaleData().getDate( GetDateTime( _rDT ) );
    }

    /*
        Creates two strings based on the distinguished name which are displayed in the
        certificate details view. The first string contains only the values of the attribute
        and valudes pairs, which are separated by commas. All escape characters ('"') are
        removed.
        The second string is for the details view at the bottom. It shows the attribute/value
        pairs on different lines. All escape characters ('"') are removed.
    */
    pair< OUString, OUString> GetDNForCertDetailsView( const OUString & rRawString)
    {
        vector< pair< OUString, OUString > > vecAttrValueOfDN = parseDN(rRawString);
        ::rtl::OUStringBuffer s1, s2;
        OUString sEqual(RTL_CONSTASCII_USTRINGPARAM(" = "));
        typedef vector< pair < OUString, OUString > >::const_iterator CIT;
        for (CIT i = vecAttrValueOfDN.begin(); i < vecAttrValueOfDN.end(); ++i)
        {
            if (i != vecAttrValueOfDN.begin())
            {
                s1.append(static_cast<sal_Unicode>(','));
                s2.append(static_cast<sal_Unicode>('\n'));
            }
            s1.append(i->second);
            s2.append(i->first);
            s2.append(sEqual);
            s2.append(i->second);
        }
        return make_pair(s1.makeStringAndClear(), s2.makeStringAndClear());
    }

/*
    Whenever the attribute value contains special characters, such as '"' or ',' (without '')
    then the value will be enclosed in double quotes by the respective Windows or NSS function
    which we use to retrieve, for example, the subject name. If double quotes appear in the value then
    they are escaped with a double quote. This function removes the escape characters.
*/
#ifdef WNT
vector< pair< OUString, OUString> > parseDN(const OUString& rRawString)
{
        vector< pair<OUString, OUString> > retVal;
        bool bInEscape = false;
        bool bInValue = false;
        bool bInType = true;
        sal_Int32 nTypeNameStart = 0;
        OUString sType;
        ::rtl::OUStringBuffer sbufValue;
        sal_Int32 length = rRawString.getLength();

        for (sal_Int32 i = 0; i < length; i++)
        {
            sal_Unicode c = rRawString[i];

            if (c == '=')
            {
                if (! bInValue)
                {
                    sType = rRawString.copy(nTypeNameStart, i - nTypeNameStart);
                    sType = sType.trim();
                    bInType = false;
                }
                else
                {
                    sbufValue.append(c);
                }
            }
            else if (c == '"')
            {
                if (!bInEscape)
                {
                    //If this is the quote is the first of the couple which enclose the
                    //whole value, because the value contains special characters
                    //then we just drop it. That is, this character must be followed by
                    //a character which is not '"'.
                    if ( i + 1 < length && rRawString[i+1] == '"')
                        bInEscape = true;
                    else
                        bInValue = !bInValue; //value is enclosed in " "
                }
                else
                {
                    //This quote is escaped by a preceding quote and therefore is
                    //part of the value
                    sbufValue.append(c);
                    bInEscape = false;
                }
            }
            else if (c == ',' || c == '+')
            {
                //The comma separate the attribute value pairs.
                //If the comma is not part of a value (the value would then be enclosed in '"'),
                //then we have reached the end of the value
                if (!bInValue)
                {
                    OSL_ASSERT(sType.getLength());
                    retVal.push_back(make_pair(sType, sbufValue.makeStringAndClear()));
                    sType = OUString();
                    //The next char is the start of the new type
                    nTypeNameStart = i + 1;
                    bInType = true;
                }
                else
                {
                    //The whole string is enclosed because it contains special characters.
                    //The enclosing '"' are not part of certificate but will be added by
                    //the function (Windows or NSS) which retrieves DN
                    sbufValue.append(c);
                }
            }
            else
            {
                if (!bInType)
                    sbufValue.append(c);
            }
        }
        if (sbufValue.getLength())
        {
            OSL_ASSERT(sType.getLength());
            retVal.push_back(make_pair(sType, sbufValue.makeStringAndClear()));
        }
        return retVal;
    }
#else
vector< pair< OUString, OUString> > parseDN(const OUString& rRawString)
    {
        vector< pair<OUString, OUString> > retVal;
        //bInEscape == true means that the preceding character is an escape character
        bool bInEscape = false;
        bool bInValue = false;
        bool bInType = true;
        sal_Int32 nTypeNameStart = 0;
        OUString sType;
        ::rtl::OUStringBuffer sbufValue;
        sal_Int32 length = rRawString.getLength();

        for (sal_Int32 i = 0; i < length; i++)
        {
            sal_Unicode c = rRawString[i];

            if (c == '=')
            {
                if (! bInValue)
                {
                    sType = rRawString.copy(nTypeNameStart, i - nTypeNameStart);
                    sType = sType.trim();
                    bInType = false;
                }
                else
                {
                    sbufValue.append(c);
                }
            }
            else if (c == '\\')
            {
                if (!bInEscape)
                {
                    bInEscape = true;
                }
                else
                { // bInEscape is true
                    sbufValue.append(c);
                    bInEscape = false;
                }
            }
            else if (c == '"')
            {
                //an unescaped '"' is either at the beginning or end of the value
                if (!bInEscape)
                {
                    if ( !bInValue)
                        bInValue = true;
                    else if (bInValue)
                        bInValue = false;
                }
                else
                {
                    //This quote is escaped by a preceding quote and therefore is
                    //part of the value
                    sbufValue.append(c);
                    bInEscape = false;
                }
            }
            else if (c == ',' || c == '+')
            {
                //The comma separate the attribute value pairs.
                //If the comma is not part of a value (the value would then be enclosed in '"'),
                //then we have reached the end of the value
                if (!bInValue)
                {
                    OSL_ASSERT(sType.getLength());
                    retVal.push_back(make_pair(sType, sbufValue.makeStringAndClear()));
                    sType = OUString();
                    //The next char is the start of the new type
                    nTypeNameStart = i + 1;
                    bInType = true;
                }
                else
                {
                    //The whole string is enclosed because it contains special characters.
                    //The enclosing '"' are not part of certificate but will be added by
                    //the function (Windows or NSS) which retrieves DN
                    sbufValue.append(c);
                }
            }
            else
            {
                if (!bInType)
                {
                    sbufValue.append(c);
                    bInEscape = false;
                }
            }
        }
        if (sbufValue.getLength())
        {
            OSL_ASSERT(sType.getLength());
            retVal.push_back(make_pair(sType, sbufValue.makeStringAndClear()));
        }
        return retVal;
    }

#endif

    String GetContentPart( const String& _rRawString )
    {
        char const * aIDs[] = { "CN", "OU", "O", "E", NULL };
        OUString retVal;
        int i = 0;
        vector< pair< OUString, OUString > > vecAttrValueOfDN = parseDN(_rRawString);
        while ( aIDs[i] )
        {
            OUString sPartId = OUString::createFromAscii( aIDs[i++] );
            typedef vector< pair < OUString, OUString > >::const_iterator CIT;
            for (CIT idn = vecAttrValueOfDN.begin(); idn != vecAttrValueOfDN.end(); ++idn)
            {
                if (idn->first.equals(sPartId))
                {
                    retVal = idn->second;
                    break;
                }
            }
            if (retVal.getLength())
                break;
        }
        return retVal;
    }

    String GetHexString( const ::com::sun::star::uno::Sequence< sal_Int8 >& _rSeq, const char* _pSep, sal_uInt16 _nLineBreak )
    {
        const sal_Int8*         pSerNumSeq = _rSeq.getConstArray();
        int                     nCnt = _rSeq.getLength();
        String                  aStr;
        const char              pHexDigs[ 17 ] = "0123456789ABCDEF";
        char                    pBuffer[ 3 ] = "  ";
        sal_uInt8                   nNum;
        sal_uInt16                  nBreakStart = _nLineBreak? _nLineBreak : 1;
        sal_uInt16                  nBreak = nBreakStart;
        for( int i = 0 ; i < nCnt ; ++i )
        {
            nNum = sal_uInt8( pSerNumSeq[ i ] );

            // exchange the buffer[0] and buffer[1], which make it consistent with Mozilla and Windows
            pBuffer[ 1 ] = pHexDigs[ nNum & 0x0F ];
            nNum >>= 4;
            pBuffer[ 0 ] = pHexDigs[ nNum ];
            aStr.AppendAscii( pBuffer );

            --nBreak;
            if( nBreak )
                aStr.AppendAscii( _pSep );
            else
            {
                nBreak = nBreakStart;
                aStr.AppendAscii( "\n" );
            }
        }

        return aStr;
    }

    long ShrinkToFitWidth( Control& _rCtrl, long _nOffs )
    {
        long    nWidth = _rCtrl.GetTextWidth( _rCtrl.GetText() );
        Size    aSize( _rCtrl.GetSizePixel() );
        nWidth += _nOffs;
        aSize.Width() = nWidth;
        _rCtrl.SetSizePixel( aSize );
        return nWidth;
    }

    void AlignAfterImage( const FixedImage& _rImage, Control& _rCtrl, long _nXOffset )
    {
        Point   aPos( _rImage.GetPosPixel() );
        Size    aSize( _rImage.GetSizePixel() );
        long    n = aPos.X();
        n += aSize.Width();
        n += _nXOffset;
        aPos.X() = n;
        n = aPos.Y();
        n += aSize.Height() / 2;                    // y-position is in the middle of the image
        n -= _rCtrl.GetSizePixel().Height() / 2;    // center Control
        aPos.Y() = n;
        _rCtrl.SetPosPixel( aPos );
    }

    void AlignAfterImage( const FixedImage& _rImage, FixedInfo& _rFI, long _nXOffset )
    {
        AlignAfterImage( _rImage, static_cast< Control& >( _rFI ), _nXOffset );
        ShrinkToFitWidth( _rFI );
    }

    void AlignAndFitImageAndControl( FixedImage& _rImage, FixedInfo& _rFI, long _nXOffset )
    {
        _rImage.SetSizePixel( _rImage.GetImage().GetSizePixel() );
        AlignAfterImage( _rImage, _rFI, _nXOffset );
    }
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>its just a const char*<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * 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_xmlsecurity.hxx"

#include "resourcemanager.hxx"

#include <vcl/svapp.hxx>
#include <vcl/fixed.hxx>
#include <svtools/stdctrl.hxx>
#include <svl/solar.hrc>
#include <unotools/syslocale.hxx>
#include <rtl/ustring.h>
#include <rtl/ustrbuf.h>
#include <vector>

using ::rtl::OUString;
using namespace std;

namespace XmlSec
{
    static ResMgr*          pResMgr = 0;
    static SvtSysLocale*    pSysLocale = 0;

    ResMgr* GetResMgr( void )
    {
        if (!pResMgr)
            pResMgr = ResMgr::CreateResMgr("xmlsec");
        return pResMgr;
    }

    const LocaleDataWrapper&    GetLocaleData( void )
    {
        if (!pSysLocale)
            pSysLocale = new SvtSysLocale;
        return pSysLocale->GetLocaleData();
    }

    DateTime GetDateTime( const ::com::sun::star::util::DateTime& _rDT )
    {
        return DateTime(
            Date( _rDT.Day, _rDT.Month, _rDT.Year ),
            Time( _rDT.Hours, _rDT.Minutes, _rDT.Seconds, _rDT.HundredthSeconds ) );
    }

    String GetDateTimeString( const ::com::sun::star::util::DateTime& _rDT )
    {
        // String with date and time information (#i20172#)
        DateTime aDT( GetDateTime( _rDT ) );
        const LocaleDataWrapper& rLoDa = GetLocaleData();
        String sRet( rLoDa.getDate( aDT ) );
        sRet += ' ';
        sRet += rLoDa.getTime( aDT );
        return sRet;
    }

    String GetDateTimeString( const rtl::OUString& _rDate, const rtl::OUString& _rTime )
    {
        String sDay( _rDate, 6, 2 );
        String sMonth( _rDate, 4, 2 );
        String sYear( _rDate, 0, 4 );

        String sHour( _rTime, 0, 2 );
        String sMin( _rTime, 4, 2 );
        String sSec( _rTime, 6, 2 );

        Date aDate( (sal_uInt16)sDay.ToInt32(), (sal_uInt16) sMonth.ToInt32(), (sal_uInt16)sYear.ToInt32() );
        Time aTime( sHour.ToInt32(), sMin.ToInt32(), sSec.ToInt32(), 0 );
        const LocaleDataWrapper& rLoDa = GetLocaleData();
        String aStr( rLoDa.getDate( aDate ) );
        aStr.AppendAscii( " " );
        aStr += rLoDa.getTime( aTime );
        return aStr;
    }

    String GetDateString( const ::com::sun::star::util::DateTime& _rDT )
    {
        return GetLocaleData().getDate( GetDateTime( _rDT ) );
    }

    /*
        Creates two strings based on the distinguished name which are displayed in the
        certificate details view. The first string contains only the values of the attribute
        and valudes pairs, which are separated by commas. All escape characters ('"') are
        removed.
        The second string is for the details view at the bottom. It shows the attribute/value
        pairs on different lines. All escape characters ('"') are removed.
    */
    pair< OUString, OUString> GetDNForCertDetailsView( const OUString & rRawString)
    {
        vector< pair< OUString, OUString > > vecAttrValueOfDN = parseDN(rRawString);
        ::rtl::OUStringBuffer s1, s2;
        OUString sEqual(RTL_CONSTASCII_USTRINGPARAM(" = "));
        typedef vector< pair < OUString, OUString > >::const_iterator CIT;
        for (CIT i = vecAttrValueOfDN.begin(); i < vecAttrValueOfDN.end(); ++i)
        {
            if (i != vecAttrValueOfDN.begin())
            {
                s1.append(static_cast<sal_Unicode>(','));
                s2.append(static_cast<sal_Unicode>('\n'));
            }
            s1.append(i->second);
            s2.append(i->first);
            s2.append(sEqual);
            s2.append(i->second);
        }
        return make_pair(s1.makeStringAndClear(), s2.makeStringAndClear());
    }

/*
    Whenever the attribute value contains special characters, such as '"' or ',' (without '')
    then the value will be enclosed in double quotes by the respective Windows or NSS function
    which we use to retrieve, for example, the subject name. If double quotes appear in the value then
    they are escaped with a double quote. This function removes the escape characters.
*/
#ifdef WNT
vector< pair< OUString, OUString> > parseDN(const OUString& rRawString)
{
        vector< pair<OUString, OUString> > retVal;
        bool bInEscape = false;
        bool bInValue = false;
        bool bInType = true;
        sal_Int32 nTypeNameStart = 0;
        OUString sType;
        ::rtl::OUStringBuffer sbufValue;
        sal_Int32 length = rRawString.getLength();

        for (sal_Int32 i = 0; i < length; i++)
        {
            sal_Unicode c = rRawString[i];

            if (c == '=')
            {
                if (! bInValue)
                {
                    sType = rRawString.copy(nTypeNameStart, i - nTypeNameStart);
                    sType = sType.trim();
                    bInType = false;
                }
                else
                {
                    sbufValue.append(c);
                }
            }
            else if (c == '"')
            {
                if (!bInEscape)
                {
                    //If this is the quote is the first of the couple which enclose the
                    //whole value, because the value contains special characters
                    //then we just drop it. That is, this character must be followed by
                    //a character which is not '"'.
                    if ( i + 1 < length && rRawString[i+1] == '"')
                        bInEscape = true;
                    else
                        bInValue = !bInValue; //value is enclosed in " "
                }
                else
                {
                    //This quote is escaped by a preceding quote and therefore is
                    //part of the value
                    sbufValue.append(c);
                    bInEscape = false;
                }
            }
            else if (c == ',' || c == '+')
            {
                //The comma separate the attribute value pairs.
                //If the comma is not part of a value (the value would then be enclosed in '"'),
                //then we have reached the end of the value
                if (!bInValue)
                {
                    OSL_ASSERT(sType.getLength());
                    retVal.push_back(make_pair(sType, sbufValue.makeStringAndClear()));
                    sType = OUString();
                    //The next char is the start of the new type
                    nTypeNameStart = i + 1;
                    bInType = true;
                }
                else
                {
                    //The whole string is enclosed because it contains special characters.
                    //The enclosing '"' are not part of certificate but will be added by
                    //the function (Windows or NSS) which retrieves DN
                    sbufValue.append(c);
                }
            }
            else
            {
                if (!bInType)
                    sbufValue.append(c);
            }
        }
        if (sbufValue.getLength())
        {
            OSL_ASSERT(sType.getLength());
            retVal.push_back(make_pair(sType, sbufValue.makeStringAndClear()));
        }
        return retVal;
    }
#else
vector< pair< OUString, OUString> > parseDN(const OUString& rRawString)
    {
        vector< pair<OUString, OUString> > retVal;
        //bInEscape == true means that the preceding character is an escape character
        bool bInEscape = false;
        bool bInValue = false;
        bool bInType = true;
        sal_Int32 nTypeNameStart = 0;
        OUString sType;
        ::rtl::OUStringBuffer sbufValue;
        sal_Int32 length = rRawString.getLength();

        for (sal_Int32 i = 0; i < length; i++)
        {
            sal_Unicode c = rRawString[i];

            if (c == '=')
            {
                if (! bInValue)
                {
                    sType = rRawString.copy(nTypeNameStart, i - nTypeNameStart);
                    sType = sType.trim();
                    bInType = false;
                }
                else
                {
                    sbufValue.append(c);
                }
            }
            else if (c == '\\')
            {
                if (!bInEscape)
                {
                    bInEscape = true;
                }
                else
                { // bInEscape is true
                    sbufValue.append(c);
                    bInEscape = false;
                }
            }
            else if (c == '"')
            {
                //an unescaped '"' is either at the beginning or end of the value
                if (!bInEscape)
                {
                    if ( !bInValue)
                        bInValue = true;
                    else if (bInValue)
                        bInValue = false;
                }
                else
                {
                    //This quote is escaped by a preceding quote and therefore is
                    //part of the value
                    sbufValue.append(c);
                    bInEscape = false;
                }
            }
            else if (c == ',' || c == '+')
            {
                //The comma separate the attribute value pairs.
                //If the comma is not part of a value (the value would then be enclosed in '"'),
                //then we have reached the end of the value
                if (!bInValue)
                {
                    OSL_ASSERT(sType.getLength());
                    retVal.push_back(make_pair(sType, sbufValue.makeStringAndClear()));
                    sType = OUString();
                    //The next char is the start of the new type
                    nTypeNameStart = i + 1;
                    bInType = true;
                }
                else
                {
                    //The whole string is enclosed because it contains special characters.
                    //The enclosing '"' are not part of certificate but will be added by
                    //the function (Windows or NSS) which retrieves DN
                    sbufValue.append(c);
                }
            }
            else
            {
                if (!bInType)
                {
                    sbufValue.append(c);
                    bInEscape = false;
                }
            }
        }
        if (sbufValue.getLength())
        {
            OSL_ASSERT(sType.getLength());
            retVal.push_back(make_pair(sType, sbufValue.makeStringAndClear()));
        }
        return retVal;
    }

#endif

    String GetContentPart( const String& _rRawString )
    {
        char const * aIDs[] = { "CN", "OU", "O", "E", NULL };
        OUString retVal;
        int i = 0;
        vector< pair< OUString, OUString > > vecAttrValueOfDN = parseDN(_rRawString);
        while ( aIDs[i] )
        {
            OUString sPartId = OUString::createFromAscii( aIDs[i++] );
            typedef vector< pair < OUString, OUString > >::const_iterator CIT;
            for (CIT idn = vecAttrValueOfDN.begin(); idn != vecAttrValueOfDN.end(); ++idn)
            {
                if (idn->first.equals(sPartId))
                {
                    retVal = idn->second;
                    break;
                }
            }
            if (retVal.getLength())
                break;
        }
        return retVal;
    }

    String GetHexString( const ::com::sun::star::uno::Sequence< sal_Int8 >& _rSeq, const char* _pSep, sal_uInt16 _nLineBreak )
    {
        const sal_Int8*         pSerNumSeq = _rSeq.getConstArray();
        int                     nCnt = _rSeq.getLength();
        String                  aStr;
        const char              pHexDigs[ 17 ] = "0123456789ABCDEF";
        char                    pBuffer[ 3 ] = "  ";
        sal_uInt8                   nNum;
        sal_uInt16                  nBreakStart = _nLineBreak? _nLineBreak : 1;
        sal_uInt16                  nBreak = nBreakStart;
        for( int i = 0 ; i < nCnt ; ++i )
        {
            nNum = sal_uInt8( pSerNumSeq[ i ] );

            // exchange the buffer[0] and buffer[1], which make it consistent with Mozilla and Windows
            pBuffer[ 1 ] = pHexDigs[ nNum & 0x0F ];
            nNum >>= 4;
            pBuffer[ 0 ] = pHexDigs[ nNum ];
            aStr.AppendAscii( pBuffer );

            --nBreak;
            if( nBreak )
                aStr.AppendAscii( _pSep );
            else
            {
                nBreak = nBreakStart;
                aStr.AppendAscii( "\n" );
            }
        }

        return aStr;
    }

    long ShrinkToFitWidth( Control& _rCtrl, long _nOffs )
    {
        long    nWidth = _rCtrl.GetTextWidth( _rCtrl.GetText() );
        Size    aSize( _rCtrl.GetSizePixel() );
        nWidth += _nOffs;
        aSize.Width() = nWidth;
        _rCtrl.SetSizePixel( aSize );
        return nWidth;
    }

    void AlignAfterImage( const FixedImage& _rImage, Control& _rCtrl, long _nXOffset )
    {
        Point   aPos( _rImage.GetPosPixel() );
        Size    aSize( _rImage.GetSizePixel() );
        long    n = aPos.X();
        n += aSize.Width();
        n += _nXOffset;
        aPos.X() = n;
        n = aPos.Y();
        n += aSize.Height() / 2;                    // y-position is in the middle of the image
        n -= _rCtrl.GetSizePixel().Height() / 2;    // center Control
        aPos.Y() = n;
        _rCtrl.SetPosPixel( aPos );
    }

    void AlignAfterImage( const FixedImage& _rImage, FixedInfo& _rFI, long _nXOffset )
    {
        AlignAfterImage( _rImage, static_cast< Control& >( _rFI ), _nXOffset );
        ShrinkToFitWidth( _rFI );
    }

    void AlignAndFitImageAndControl( FixedImage& _rImage, FixedInfo& _rFI, long _nXOffset )
    {
        _rImage.SetSizePixel( _rImage.GetImage().GetSizePixel() );
        AlignAfterImage( _rImage, _rFI, _nXOffset );
    }
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: decryptorimpl.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2005-03-10 18:06:24 $
 *
 *  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: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _DECRYPTORIMPL_HXX
#define _DECRYPTORIMPL_HXX

#ifndef _COM_SUN_STAR_XML_CRYPTO_SAX_XDECRYPTIONRESULTBROADCASTER_HPP_
#include <com/sun/star/xml/crypto/sax/XDecryptionResultBroadcaster.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_CRYPTO_SAX_XDECRYPTIONRESULTLISTENER_HPP_
#include <com/sun/star/xml/crypto/sax/XDecryptionResultListener.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_CRYPTO_XXMLSECURITYCONTEXT_HPP_
#include <com/sun/star/xml/crypto/XXMLSecurityContext.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif

#include "encryptionengine.hxx"

class DecryptorImpl : public cppu::ImplInheritanceHelper3
<
    EncryptionEngine,
    com::sun::star::xml::crypto::sax::XDecryptionResultBroadcaster,
    com::sun::star::lang::XInitialization,
    com::sun::star::lang::XServiceInfo
>
/****** DecryptorImpl.hxx/CLASS DecryptorImpl *********************************
 *
 *   NAME
 *  DecryptorImpl -- decrypts an encryption
 *
 *   FUNCTION
 *  Collects all resources for decrypting an encryption, then decrypts the
 *  encryption by invoking a xmlsec-based encryption bridge component.
 *
 *   HISTORY
 *  05.01.2004 -    Interface supported: XDecryptionResultBroadcaster,
 *                  XInitialization, XServiceInfo
 *
 *   AUTHOR
 *  Michael Mi
 *  Email: michael.mi@sun.com
 ******************************************************************************/
{
private:
    /*
     * the Id of the encryption, which is used for the result listener to
     * identify the encryption.
     */
    sal_Int32 m_nEncryptionId;

    /*
     * the decryption result,
     * remembers whether the decryption succeeds.
     */
    bool      m_bDecryptionSucceed;

    com::sun::star::uno::Reference<
        com::sun::star::xml::crypto::XXMLSecurityContext > m_xXMLSecurityContext;

    virtual void notifyResultListener() const
        throw (com::sun::star::uno::Exception, com::sun::star::uno::RuntimeException);
    virtual bool checkReady() const;
    virtual void startEngine( const com::sun::star::uno::Reference<
        com::sun::star::xml::crypto::XXMLEncryptionTemplate >&
        xEncryptionTemplate)
        throw (com::sun::star::uno::Exception, com::sun::star::uno::RuntimeException);

public:
    explicit DecryptorImpl( const com::sun::star::uno::Reference<
        com::sun::star::lang::XMultiServiceFactory >& rxMSF);
    virtual ~DecryptorImpl();

    /* XDecryptionResultBroadcaster */
    virtual void SAL_CALL addDecryptionResultListener(
        const com::sun::star::uno::Reference<
            com::sun::star::xml::crypto::sax::XDecryptionResultListener >&
            listener )
            throw (com::sun::star::uno::Exception, com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL removeDecryptionResultListener(
            const com::sun::star::uno::Reference<
                com::sun::star::xml::crypto::sax::XDecryptionResultListener >&
                listener )
            throw (com::sun::star::uno::RuntimeException);

    /* XInitialization */
    virtual void SAL_CALL initialize(
        const com::sun::star::uno::Sequence< com::sun::star::uno::Any >& aArguments )
        throw (com::sun::star::uno::Exception, com::sun::star::uno::RuntimeException);

    /* XServiceInfo */
    virtual rtl::OUString SAL_CALL getImplementationName(  )
        throw (com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const rtl::OUString& ServiceName )
        throw (com::sun::star::uno::RuntimeException);
    virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames(  )
        throw (com::sun::star::uno::RuntimeException);
};

rtl::OUString DecryptorImpl_getImplementationName()
    throw ( com::sun::star::uno::RuntimeException );

sal_Bool SAL_CALL DecryptorImpl_supportsService( const rtl::OUString& ServiceName )
    throw ( com::sun::star::uno::RuntimeException );

com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL DecryptorImpl_getSupportedServiceNames(  )
    throw ( com::sun::star::uno::RuntimeException );

com::sun::star::uno::Reference< com::sun::star::uno::XInterface >
SAL_CALL DecryptorImpl_createInstance(
    const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >&
        rSMgr)
    throw ( com::sun::star::uno::Exception );

#endif

<commit_msg>INTEGRATION: CWS ooo19126 (1.2.52); FILE MERGED 2005/09/05 17:01:41 rt 1.2.52.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: decryptorimpl.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 17:15:18 $
 *
 *  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 _DECRYPTORIMPL_HXX
#define _DECRYPTORIMPL_HXX

#ifndef _COM_SUN_STAR_XML_CRYPTO_SAX_XDECRYPTIONRESULTBROADCASTER_HPP_
#include <com/sun/star/xml/crypto/sax/XDecryptionResultBroadcaster.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_CRYPTO_SAX_XDECRYPTIONRESULTLISTENER_HPP_
#include <com/sun/star/xml/crypto/sax/XDecryptionResultListener.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_CRYPTO_XXMLSECURITYCONTEXT_HPP_
#include <com/sun/star/xml/crypto/XXMLSecurityContext.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif

#include "encryptionengine.hxx"

class DecryptorImpl : public cppu::ImplInheritanceHelper3
<
    EncryptionEngine,
    com::sun::star::xml::crypto::sax::XDecryptionResultBroadcaster,
    com::sun::star::lang::XInitialization,
    com::sun::star::lang::XServiceInfo
>
/****** DecryptorImpl.hxx/CLASS DecryptorImpl *********************************
 *
 *   NAME
 *  DecryptorImpl -- decrypts an encryption
 *
 *   FUNCTION
 *  Collects all resources for decrypting an encryption, then decrypts the
 *  encryption by invoking a xmlsec-based encryption bridge component.
 *
 *   HISTORY
 *  05.01.2004 -    Interface supported: XDecryptionResultBroadcaster,
 *                  XInitialization, XServiceInfo
 *
 *   AUTHOR
 *  Michael Mi
 *  Email: michael.mi@sun.com
 ******************************************************************************/
{
private:
    /*
     * the Id of the encryption, which is used for the result listener to
     * identify the encryption.
     */
    sal_Int32 m_nEncryptionId;

    /*
     * the decryption result,
     * remembers whether the decryption succeeds.
     */
    bool      m_bDecryptionSucceed;

    com::sun::star::uno::Reference<
        com::sun::star::xml::crypto::XXMLSecurityContext > m_xXMLSecurityContext;

    virtual void notifyResultListener() const
        throw (com::sun::star::uno::Exception, com::sun::star::uno::RuntimeException);
    virtual bool checkReady() const;
    virtual void startEngine( const com::sun::star::uno::Reference<
        com::sun::star::xml::crypto::XXMLEncryptionTemplate >&
        xEncryptionTemplate)
        throw (com::sun::star::uno::Exception, com::sun::star::uno::RuntimeException);

public:
    explicit DecryptorImpl( const com::sun::star::uno::Reference<
        com::sun::star::lang::XMultiServiceFactory >& rxMSF);
    virtual ~DecryptorImpl();

    /* XDecryptionResultBroadcaster */
    virtual void SAL_CALL addDecryptionResultListener(
        const com::sun::star::uno::Reference<
            com::sun::star::xml::crypto::sax::XDecryptionResultListener >&
            listener )
            throw (com::sun::star::uno::Exception, com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL removeDecryptionResultListener(
            const com::sun::star::uno::Reference<
                com::sun::star::xml::crypto::sax::XDecryptionResultListener >&
                listener )
            throw (com::sun::star::uno::RuntimeException);

    /* XInitialization */
    virtual void SAL_CALL initialize(
        const com::sun::star::uno::Sequence< com::sun::star::uno::Any >& aArguments )
        throw (com::sun::star::uno::Exception, com::sun::star::uno::RuntimeException);

    /* XServiceInfo */
    virtual rtl::OUString SAL_CALL getImplementationName(  )
        throw (com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const rtl::OUString& ServiceName )
        throw (com::sun::star::uno::RuntimeException);
    virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames(  )
        throw (com::sun::star::uno::RuntimeException);
};

rtl::OUString DecryptorImpl_getImplementationName()
    throw ( com::sun::star::uno::RuntimeException );

sal_Bool SAL_CALL DecryptorImpl_supportsService( const rtl::OUString& ServiceName )
    throw ( com::sun::star::uno::RuntimeException );

com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL DecryptorImpl_getSupportedServiceNames(  )
    throw ( com::sun::star::uno::RuntimeException );

com::sun::star::uno::Reference< com::sun::star::uno::XInterface >
SAL_CALL DecryptorImpl_createInstance(
    const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >&
        rSMgr)
    throw ( com::sun::star::uno::Exception );

#endif

<|endoftext|>


<commit_before>#include "types.h"
#include "amd64.h"
#include "kernel.hh"
#include "percpu.hh"
#include "wq.hh"
#include "kalloc.hh"
#include "cpputil.hh"

extern "C" void zpage(void*);
extern "C" void zrun_nc(run*);

static const bool prezero = true;

struct zallocator {
  kmem   kmem;
  wframe frame;

  void  init(int);
  char* alloc(const char*);
  void  free(void*);
  void  tryrefill();
};
percpu<zallocator> z_;

struct zwork : public work {
  zwork(wframe* frame, zallocator* zer)
    : frame_(frame), zer_(zer)
  {
    frame_->inc();
  }

  virtual void run() {
    for (int i = 0; i < 32; i++) {
      struct run* r = (struct run*)kalloc("zpage");
      if (r == nullptr)
        break;
      zrun_nc(r);
      zer_->kmem.free(r);
    }
    frame_->dec();
    delete this;
  }

  wframe* frame_;
  zallocator* zer_;

  NEW_DELETE_OPS(zwork);
};

//
// zallocator
//
void
zallocator::tryrefill(void)
{
  if (prezero && kmem.nfree < 16 && frame.zero()) {
    zwork* w = new zwork(&frame, this);
    if (wq_push(w) < 0)
      delete w;
  }
}

void
zallocator::init(int c)
{
  frame.clear();
  kmem.name[0] = (char) c + '0';
  safestrcpy(kmem.name+1, "zmem", MAXNAME-1);
  kmem.size = PGSIZE;
}

char*
zallocator::alloc(const char* name)
{
  char* p;

  p = (char*) kmem.alloc(name);
  if (p == nullptr) {
    p = kalloc(name);
    if (p != nullptr)
      zpage(p);
  } else {
    // Zero the run header used by kmem
    memset(p, 0, sizeof(struct run));
    if (0)
      for (int i = 0; i < PGSIZE; i++)
        assert(p[i] == 0);
  }
  tryrefill();
  return p;
}

void
zallocator::free(void* p)
{
  if (0)
    for (int i = 0; i < 4096; i++)
      assert(((char*)p)[i] == 0);

  kmem.free((struct run*)p);
}

char*
zalloc(const char* name)
{
  return z_->alloc(name);
}

void
zfree(void* p)
{
  z_->free(p);
}

void
initz(void)
{
  for (int c = 0; c < NCPU; c++)
    z_[c].init(c);
}
<commit_msg>Comment zalloc and zfree since I always forget that they aren't a pair<commit_after>#include "types.h"
#include "amd64.h"
#include "kernel.hh"
#include "percpu.hh"
#include "wq.hh"
#include "kalloc.hh"
#include "cpputil.hh"

extern "C" void zpage(void*);
extern "C" void zrun_nc(run*);

static const bool prezero = true;

struct zallocator {
  kmem   kmem;
  wframe frame;

  void  init(int);
  char* alloc(const char*);
  void  free(void*);
  void  tryrefill();
};
percpu<zallocator> z_;

struct zwork : public work {
  zwork(wframe* frame, zallocator* zer)
    : frame_(frame), zer_(zer)
  {
    frame_->inc();
  }

  virtual void run() {
    for (int i = 0; i < 32; i++) {
      struct run* r = (struct run*)kalloc("zpage");
      if (r == nullptr)
        break;
      zrun_nc(r);
      zer_->kmem.free(r);
    }
    frame_->dec();
    delete this;
  }

  wframe* frame_;
  zallocator* zer_;

  NEW_DELETE_OPS(zwork);
};

//
// zallocator
//
void
zallocator::tryrefill(void)
{
  if (prezero && kmem.nfree < 16 && frame.zero()) {
    zwork* w = new zwork(&frame, this);
    if (wq_push(w) < 0)
      delete w;
  }
}

void
zallocator::init(int c)
{
  frame.clear();
  kmem.name[0] = (char) c + '0';
  safestrcpy(kmem.name+1, "zmem", MAXNAME-1);
  kmem.size = PGSIZE;
}

char*
zallocator::alloc(const char* name)
{
  char* p;

  p = (char*) kmem.alloc(name);
  if (p == nullptr) {
    p = kalloc(name);
    if (p != nullptr)
      zpage(p);
  } else {
    // Zero the run header used by kmem
    memset(p, 0, sizeof(struct run));
    if (0)
      for (int i = 0; i < PGSIZE; i++)
        assert(p[i] == 0);
  }
  tryrefill();
  return p;
}

void
zallocator::free(void* p)
{
  if (0)
    for (int i = 0; i < 4096; i++)
      assert(((char*)p)[i] == 0);

  kmem.free((struct run*)p);
}

// Allocate a zeroed page.  This page can be freed with kfree or, if
// it is known to be zeroed when it is freed, zfree.
char*
zalloc(const char* name)
{
  return z_->alloc(name);
}

// Free a page that is known to be zero
void
zfree(void* p)
{
  z_->free(p);
}

void
initz(void)
{
  for (int c = 0; c < NCPU; c++)
    z_[c].init(c);
}
<|endoftext|>