<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: propbrw.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: kz $ $Date: 2008-03-06 19:15:10 $
 *
 *  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 _BASCTL_PROPBRW_HXX
#define _BASCTL_PROPBRW_HXX

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#ifndef _COM_SUN_STAR_AWT_XCONTROLCONTAINER_HPP_
#include <com/sun/star/awt/XControlContainer.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif

#ifndef _COMPHELPER_COMPOSEDPROPS_HXX_
#include <comphelper/composedprops.hxx>
#endif

#ifndef _BASEDLGS_HXX
#include <sfx2/basedlgs.hxx>
#endif

#ifndef _SFXBRDCST_HXX //autogen
#include <svtools/brdcst.hxx>
#endif

#ifndef _SFXLSTNER_HXX //autogen
#include <svtools/lstner.hxx>
#endif

#ifndef _SFX_CHILDWIN_HXX
#include <sfx2/childwin.hxx>
#endif

#ifndef _SVDMARK_HXX //autogen
#include <svx/svdmark.hxx>
#endif

//============================================================================
// PropBrwMgr
//============================================================================

class PropBrwMgr : public SfxChildWindow
{
public:
    PropBrwMgr(Window *pParent, sal_uInt16 nId, SfxBindings *pBindings, SfxChildWinInfo *pInfo);
    SFX_DECL_CHILDWINDOW(PropBrwMgr);
};

//============================================================================
// PropBrw
//============================================================================

class SfxBindings;
class SdrView;

class PropBrw : public SfxFloatingWindow , public SfxListener, public SfxBroadcaster
{
private:
    sal_Bool        m_bInitialStateChange;

    ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >
                    m_xORB;
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >
                    m_xMeAsFrame;
    ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >
                    m_xBrowserController;
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow >
                    m_xBrowserComponentWindow;
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >
                    m_xContextDocument;

protected:
    SdrView*        pView;
    virtual void Resize();
    virtual void FillInfo( SfxChildWinInfo& rInfo ) const;
    virtual sal_Bool Close();

    DECLARE_STL_VECTOR(::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface>, InterfaceArray);

    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > >
        CreateMultiSelectionSequence( const SdrMarkList& _rMarkList );
    void implSetNewObjectSequence( const ::com::sun::star::uno::Sequence
        < ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > >& _rObjectSeq );

    void implSetNewObject(
        const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxObject);

    ::rtl::OUString GetHeadlineName(
        const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxObject);

public:
    PropBrw( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _xORB,
             SfxBindings *pBindings,
             PropBrwMgr* pMgr,
             Window* pParent,
             const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& _rxContextDocument
    );
    virtual ~PropBrw();
    using Window::Update;
    // note: changing the Context document to an instance other than the one given in the ctor is not supported
    // currently
    void    Update( const SfxViewShell* _pShell );
    SdrView*        GetCurView() const { return pView; }

private:
    void    ImplUpdate( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& _rxContextDocument, SdrView* pView );
    void    ImplDestroyController();
    void    ImplReCreateController();
};

#endif // _BASCTL_PROPBRW_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.7.2); FILE MERGED 2008/04/01 15:00:42 thb 1.7.2.3: #i85898# Stripping all external header guards 2008/04/01 10:47:48 thb 1.7.2.2: #i85898# Stripping all external header guards 2008/03/28 16:05:06 rt 1.7.2.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: propbrw.hxx,v $
 * $Revision: 1.8 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _BASCTL_PROPBRW_HXX
#define _BASCTL_PROPBRW_HXX

#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/awt/XControlContainer.hpp>
#include <com/sun/star/frame/XFrame.hpp>
#include <comphelper/composedprops.hxx>
#include <sfx2/basedlgs.hxx>
#include <svtools/brdcst.hxx>
#include <svtools/lstner.hxx>
#include <sfx2/childwin.hxx>
#include <svx/svdmark.hxx>

//============================================================================
// PropBrwMgr
//============================================================================

class PropBrwMgr : public SfxChildWindow
{
public:
    PropBrwMgr(Window *pParent, sal_uInt16 nId, SfxBindings *pBindings, SfxChildWinInfo *pInfo);
    SFX_DECL_CHILDWINDOW(PropBrwMgr);
};

//============================================================================
// PropBrw
//============================================================================

class SfxBindings;
class SdrView;

class PropBrw : public SfxFloatingWindow , public SfxListener, public SfxBroadcaster
{
private:
    sal_Bool        m_bInitialStateChange;

    ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >
                    m_xORB;
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >
                    m_xMeAsFrame;
    ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >
                    m_xBrowserController;
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow >
                    m_xBrowserComponentWindow;
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >
                    m_xContextDocument;

protected:
    SdrView*        pView;
    virtual void Resize();
    virtual void FillInfo( SfxChildWinInfo& rInfo ) const;
    virtual sal_Bool Close();

    DECLARE_STL_VECTOR(::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface>, InterfaceArray);

    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > >
        CreateMultiSelectionSequence( const SdrMarkList& _rMarkList );
    void implSetNewObjectSequence( const ::com::sun::star::uno::Sequence
        < ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > >& _rObjectSeq );

    void implSetNewObject(
        const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxObject);

    ::rtl::OUString GetHeadlineName(
        const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxObject);

public:
    PropBrw( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _xORB,
             SfxBindings *pBindings,
             PropBrwMgr* pMgr,
             Window* pParent,
             const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& _rxContextDocument
    );
    virtual ~PropBrw();
    using Window::Update;
    // note: changing the Context document to an instance other than the one given in the ctor is not supported
    // currently
    void    Update( const SfxViewShell* _pShell );
    SdrView*        GetCurView() const { return pView; }

private:
    void    ImplUpdate( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& _rxContextDocument, SdrView* pView );
    void    ImplDestroyController();
    void    ImplReCreateController();
};

#endif // _BASCTL_PROPBRW_HXX
<|endoftext|>


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

#include "base/metrics/sample_vector.h"

#include "base/logging.h"
#include "base/metrics/bucket_ranges.h"

using std::vector;

namespace base {

typedef HistogramBase::Count Count;
typedef HistogramBase::Sample Sample;

SampleVector::SampleVector(const BucketRanges* bucket_ranges)
    : counts_(bucket_ranges->size() - 1),
      bucket_ranges_(bucket_ranges) {
  CHECK_GE(bucket_ranges_->size(), 2u);
}

SampleVector::~SampleVector() {}

void SampleVector::Accumulate(Sample value, Count count) {
  size_t bucket_index = GetBucketIndex(value);
  counts_[bucket_index] += count;
  IncreaseSum(count * value);
  IncreaseRedundantCount(count);
}

Count SampleVector::GetCount(Sample value) const {
  size_t bucket_index = GetBucketIndex(value);
  return counts_[bucket_index];
}

Count SampleVector::TotalCount() const {
  Count count = 0;
  for (size_t i = 0; i < counts_.size(); i++) {
    count += counts_[i];
  }
  return count;
}

Count SampleVector::GetCountAtIndex(size_t bucket_index) const {
  DCHECK(bucket_index >= 0 && bucket_index < counts_.size());
  return counts_[bucket_index];
}

scoped_ptr<SampleCountIterator> SampleVector::Iterator() const {
  return scoped_ptr<SampleCountIterator>(
      new SampleVectorIterator(&counts_, bucket_ranges_));
}

bool SampleVector::AddSubtractImpl(SampleCountIterator* iter,
                                   HistogramSamples::Operator op) {
  HistogramBase::Sample min;
  HistogramBase::Sample max;
  HistogramBase::Count count;

  // Go through the iterator and add the counts into correct bucket.
  size_t index = 0;
  while (index < counts_.size() && !iter->Done()) {
    iter->Get(&min, &max, &count);
    if (min == bucket_ranges_->range(index) &&
        max == bucket_ranges_->range(index + 1)) {
      // Sample matches this bucket!
      counts_[index] += (op ==  HistogramSamples::ADD) ? count : -count;
      iter->Next();
    } else if (min > bucket_ranges_->range(index)) {
      // Sample is larger than current bucket range. Try next.
      index++;
    } else {
      // Sample is smaller than current bucket range. We scan buckets from
      // smallest to largest, so the sample value must be invalid.
      return false;
    }
  }

  return iter->Done();
}

// Use simple binary search.  This is very general, but there are better
// approaches if we knew that the buckets were linearly distributed.
size_t SampleVector::GetBucketIndex(Sample value) const {
  size_t bucket_count = bucket_ranges_->size() - 1;
  CHECK_GE(bucket_count, 1u);
  CHECK_GE(value, bucket_ranges_->range(0));
  CHECK_LT(value, bucket_ranges_->range(bucket_count));

  size_t under = 0;
  size_t over = bucket_count;
  size_t mid;
  do {
    DCHECK_GE(over, under);
    mid = under + (over - under)/2;
    if (mid == under)
      break;
    if (bucket_ranges_->range(mid) <= value)
      under = mid;
    else
      over = mid;
  } while (true);

  DCHECK_LE(bucket_ranges_->range(mid), value);
  CHECK_GT(bucket_ranges_->range(mid + 1), value);
  return mid;
}

SampleVectorIterator::SampleVectorIterator(const vector<Count>* counts,
                                           const BucketRanges* bucket_ranges)
    : counts_(counts),
      bucket_ranges_(bucket_ranges),
      index_(0) {
  CHECK_GT(bucket_ranges_->size(), counts_->size());
  SkipEmptyBuckets();
}

SampleVectorIterator::~SampleVectorIterator() {}

bool SampleVectorIterator::Done() const {
  return index_ >= counts_->size();
}

void SampleVectorIterator::Next() {
  DCHECK(!Done());
  index_++;
  SkipEmptyBuckets();
}

void SampleVectorIterator::Get(HistogramBase::Sample* min,
                               HistogramBase::Sample* max,
                               HistogramBase::Count* count) const {
  DCHECK(!Done());
  if (min != NULL)
    *min = bucket_ranges_->range(index_);
  if (max != NULL)
    *max = bucket_ranges_->range(index_ + 1);
  if (count != NULL)
    *count = (*counts_)[index_];
}

bool SampleVectorIterator::GetBucketIndex(size_t* index) const {
  DCHECK(!Done());
  if (index != NULL)
    *index = index_;
  return true;
}

void SampleVectorIterator::SkipEmptyBuckets() {
  if (Done())
    return;

  while (index_ < counts_->size()) {
    if ((*counts_)[index_] != 0)
      return;
    index_++;
  }
}

}  // namespace base
<commit_msg>remove redundant DCHECK that a size_t variable >= 0<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/metrics/sample_vector.h"

#include "base/logging.h"
#include "base/metrics/bucket_ranges.h"

using std::vector;

namespace base {

typedef HistogramBase::Count Count;
typedef HistogramBase::Sample Sample;

SampleVector::SampleVector(const BucketRanges* bucket_ranges)
    : counts_(bucket_ranges->size() - 1),
      bucket_ranges_(bucket_ranges) {
  CHECK_GE(bucket_ranges_->size(), 2u);
}

SampleVector::~SampleVector() {}

void SampleVector::Accumulate(Sample value, Count count) {
  size_t bucket_index = GetBucketIndex(value);
  counts_[bucket_index] += count;
  IncreaseSum(count * value);
  IncreaseRedundantCount(count);
}

Count SampleVector::GetCount(Sample value) const {
  size_t bucket_index = GetBucketIndex(value);
  return counts_[bucket_index];
}

Count SampleVector::TotalCount() const {
  Count count = 0;
  for (size_t i = 0; i < counts_.size(); i++) {
    count += counts_[i];
  }
  return count;
}

Count SampleVector::GetCountAtIndex(size_t bucket_index) const {
  DCHECK(bucket_index < counts_.size());
  return counts_[bucket_index];
}

scoped_ptr<SampleCountIterator> SampleVector::Iterator() const {
  return scoped_ptr<SampleCountIterator>(
      new SampleVectorIterator(&counts_, bucket_ranges_));
}

bool SampleVector::AddSubtractImpl(SampleCountIterator* iter,
                                   HistogramSamples::Operator op) {
  HistogramBase::Sample min;
  HistogramBase::Sample max;
  HistogramBase::Count count;

  // Go through the iterator and add the counts into correct bucket.
  size_t index = 0;
  while (index < counts_.size() && !iter->Done()) {
    iter->Get(&min, &max, &count);
    if (min == bucket_ranges_->range(index) &&
        max == bucket_ranges_->range(index + 1)) {
      // Sample matches this bucket!
      counts_[index] += (op ==  HistogramSamples::ADD) ? count : -count;
      iter->Next();
    } else if (min > bucket_ranges_->range(index)) {
      // Sample is larger than current bucket range. Try next.
      index++;
    } else {
      // Sample is smaller than current bucket range. We scan buckets from
      // smallest to largest, so the sample value must be invalid.
      return false;
    }
  }

  return iter->Done();
}

// Use simple binary search.  This is very general, but there are better
// approaches if we knew that the buckets were linearly distributed.
size_t SampleVector::GetBucketIndex(Sample value) const {
  size_t bucket_count = bucket_ranges_->size() - 1;
  CHECK_GE(bucket_count, 1u);
  CHECK_GE(value, bucket_ranges_->range(0));
  CHECK_LT(value, bucket_ranges_->range(bucket_count));

  size_t under = 0;
  size_t over = bucket_count;
  size_t mid;
  do {
    DCHECK_GE(over, under);
    mid = under + (over - under)/2;
    if (mid == under)
      break;
    if (bucket_ranges_->range(mid) <= value)
      under = mid;
    else
      over = mid;
  } while (true);

  DCHECK_LE(bucket_ranges_->range(mid), value);
  CHECK_GT(bucket_ranges_->range(mid + 1), value);
  return mid;
}

SampleVectorIterator::SampleVectorIterator(const vector<Count>* counts,
                                           const BucketRanges* bucket_ranges)
    : counts_(counts),
      bucket_ranges_(bucket_ranges),
      index_(0) {
  CHECK_GT(bucket_ranges_->size(), counts_->size());
  SkipEmptyBuckets();
}

SampleVectorIterator::~SampleVectorIterator() {}

bool SampleVectorIterator::Done() const {
  return index_ >= counts_->size();
}

void SampleVectorIterator::Next() {
  DCHECK(!Done());
  index_++;
  SkipEmptyBuckets();
}

void SampleVectorIterator::Get(HistogramBase::Sample* min,
                               HistogramBase::Sample* max,
                               HistogramBase::Count* count) const {
  DCHECK(!Done());
  if (min != NULL)
    *min = bucket_ranges_->range(index_);
  if (max != NULL)
    *max = bucket_ranges_->range(index_ + 1);
  if (count != NULL)
    *count = (*counts_)[index_];
}

bool SampleVectorIterator::GetBucketIndex(size_t* index) const {
  DCHECK(!Done());
  if (index != NULL)
    *index = index_;
  return true;
}

void SampleVectorIterator::SkipEmptyBuckets() {
  if (Done())
    return;

  while (index_ < counts_->size()) {
    if ((*counts_)[index_] != 0)
      return;
    index_++;
  }
}

}  // namespace base
<|endoftext|>


<commit_before><commit_msg>bug fix<commit_after><|endoftext|>


<commit_before>#include "timer.h"

#include <iostream>
#include <sstream>
#include <cassert>

#include <Atlas/Codecs/Packed.h>
#include <Atlas/Codecs/XML.h>
#include <Atlas/Objects/Operation.h>
#include <Atlas/Objects/Encoder.h>
#include <Atlas/Message/QueuedDecoder.h>
#include <Atlas/Message/MEncoder.h>
#include <Atlas/Objects/Entity.h>

using Atlas::Message::Element;
using Atlas::Message::MapType;
using Atlas::Message::ListType;

int main(int argc, char** argv)
{
    long long i;

    Atlas::Objects::Entity::Anonymous anon;
    anon->setLoc("12345");
    ListType velocity;
    velocity.push_back(1.4);
    velocity.push_back(2.4);
    velocity.push_back(3.4);
    anon->setVelocityAsList(velocity);
    ListType bbox;
    bbox.push_back(1.4);
    bbox.push_back(2.4);
    bbox.push_back(3.4);
    bbox.push_back(2.4);
    anon->setAttr("bbox", bbox);

    Atlas::Objects::Operation::Move move;
    move->setFrom("123456");
    move->setTo("123456");
    move->setSeconds(12345678);
    move->setId("123456");
    move->setArgs1(anon);

    Atlas::Objects::Operation::Sight sight;
    sight->setFrom("123456");
    sight->setTo("123456");
    sight->setSeconds(12345678);
    sight->setId("123456");
    sight->setArgs1(move);

    const MapType map = sight->asMessage();

    std::string message;

    //Warm up process first
    for (i = 0; i < 100000000; i += 1) {
        Atlas::Message::Element element;
    }

    {
        TIME_ON
        for (i = 0; i < 1000000; i += 1) {
            Atlas::Message::Element element(
                    std::string(
                            "fdf adda ds dsafds asdfdasdsafdsdsaffdsdsadsafdds a dsf dsdfsads fdsads adsasa"));
        }
        TIME_OFF("Element string ctor");
    }

    {
        TIME_ON
        for (i = 0; i < 1000000; i += 1) {
            Atlas::Message::Element element;
            element =
                    std::string(
                            "fdf adda ds dsafds asdfdasdsafdsdsaffdsdsadsafdds a dsf dsdfsads fdsads adsasa");
        }
        TIME_OFF("Element string rvalue assign");
    }

    {
        TIME_ON
        for (i = 0; i < 1000000; i += 1) {
            Atlas::Message::Element element;
            const std::string aString(
                    "fdf adda ds dsafds asdfdasdsafdsdsaffdsdsadsafdds a dsf dsdfsads fdsads adsasa");
            element = aString;
        }
        TIME_OFF("Element string assign");
    }

    {
        TIME_ON
        for (i = 0; i < 1000000; i += 1) {
            Atlas::Message::Element element;
            std::string aString(
                    "fdf adda ds dsafds asdfdasdsafdsdsaffdsdsadsafdds a dsf dsdfsads fdsads adsasa");
            element = std::move(aString);
        }
        TIME_OFF("Element string move assign");
    }

    {
        TIME_ON
        for (i = 0; i < 1000000; i += 1) {
            Atlas::Message::Element element(
                    "fdf adda ds dsafds asdfdasdsafdsdsaffdsdsadsafdds a dsf dsdfsads fdsads adsasa");
        }
        TIME_OFF("Element char* ctor");
    }

    {
        TIME_ON
        for (i = 0; i < 1000000; i += 1) {
            Atlas::Message::Element element;
            element =
                    "fdf adda ds dsafds asdfdasdsafdsdsaffdsdsadsafdds a dsf dsdfsads fdsads adsasa";
        }
        TIME_OFF("Element char* assign");
    }

    {
        TIME_ON
        for (i = 0; i < 1000000; i += 1.0) {
            MapType mapCopy = map;
            Atlas::Message::Element element(std::move(mapCopy));
        }
        TIME_OFF("Element move ctor");
    }

    {
        TIME_ON
        for (i = 0; i < 1000000; i += 1.0) {
            MapType mapCopy = map;
            Atlas::Message::Element element;
            element = std::move(mapCopy);
        }
        TIME_OFF("Element move assign");
    }

    {
        TIME_ON
        for (i = 0; i < 1000000; i += 1.0) {
            MapType mapCopy = map;
            Atlas::Message::Element element(mapCopy);
        }
        TIME_OFF("Element ctor");
    }

    {
        TIME_ON
        for (i = 0; i < 1000000; i += 1.0) {
            MapType mapCopy = map;
            Atlas::Message::Element element;
            element = mapCopy;
        }
        TIME_OFF("Element assign");
    }

    return 0;
}
<commit_msg>Benchmarks for getting map from Object.<commit_after>#include "timer.h"

#include <iostream>
#include <sstream>
#include <cassert>

#include <Atlas/Codecs/Packed.h>
#include <Atlas/Codecs/XML.h>
#include <Atlas/Objects/Operation.h>
#include <Atlas/Objects/Encoder.h>
#include <Atlas/Message/QueuedDecoder.h>
#include <Atlas/Message/MEncoder.h>
#include <Atlas/Objects/Entity.h>

using Atlas::Message::Element;
using Atlas::Message::MapType;
using Atlas::Message::ListType;

int main(int argc, char** argv)
{
    long long i;

    Atlas::Objects::Entity::Anonymous anon;
    anon->setLoc("12345");
    ListType velocity;
    velocity.push_back(1.4);
    velocity.push_back(2.4);
    velocity.push_back(3.4);
    anon->setVelocityAsList(velocity);
    ListType bbox;
    bbox.push_back(1.4);
    bbox.push_back(2.4);
    bbox.push_back(3.4);
    bbox.push_back(2.4);
    anon->setAttr("bbox", bbox);

    Atlas::Objects::Operation::Move move;
    move->setFrom("123456");
    move->setTo("123456");
    move->setSeconds(12345678);
    move->setId("123456");
    move->setArgs1(anon);

    Atlas::Objects::Operation::Sight sight;
    sight->setFrom("123456");
    sight->setTo("123456");
    sight->setSeconds(12345678);
    sight->setId("123456");
    sight->setArgs1(move);

    const MapType map = sight->asMessage();

    std::string message;

    //Warm up process first
    for (i = 0; i < 100000000; i += 1) {
        Atlas::Message::Element element;
    }
    {
        TIME_ON
        for (i = 0; i < 200000; i += 1) {
            MapType map = sight->asMessage();
        }
        TIME_OFF("BaseObject::asMessage");
    }
    {
        TIME_ON
        for (i = 0; i < 200000; i += 1) {
            MapType map;
            sight->addToMessage(map);
        }
        TIME_OFF("BaseObject::addToMessage");
    }

    {
        TIME_ON
        for (i = 0; i < 1000000; i += 1) {
            Atlas::Message::Element element(
                    std::string(
                            "fdf adda ds dsafds asdfdasdsafdsdsaffdsdsadsafdds a dsf dsdfsads fdsads adsasa"));
        }
        TIME_OFF("Element string ctor");
    }

    {
        TIME_ON
        for (i = 0; i < 1000000; i += 1) {
            Atlas::Message::Element element;
            element =
                    std::string(
                            "fdf adda ds dsafds asdfdasdsafdsdsaffdsdsadsafdds a dsf dsdfsads fdsads adsasa");
        }
        TIME_OFF("Element string rvalue assign");
    }

    {
        TIME_ON
        for (i = 0; i < 1000000; i += 1) {
            Atlas::Message::Element element;
            const std::string aString(
                    "fdf adda ds dsafds asdfdasdsafdsdsaffdsdsadsafdds a dsf dsdfsads fdsads adsasa");
            element = aString;
        }
        TIME_OFF("Element string assign");
    }

    {
        TIME_ON
        for (i = 0; i < 1000000; i += 1) {
            Atlas::Message::Element element;
            std::string aString(
                    "fdf adda ds dsafds asdfdasdsafdsdsaffdsdsadsafdds a dsf dsdfsads fdsads adsasa");
            element = std::move(aString);
        }
        TIME_OFF("Element string move assign");
    }

    {
        TIME_ON
        for (i = 0; i < 1000000; i += 1) {
            Atlas::Message::Element element(
                    "fdf adda ds dsafds asdfdasdsafdsdsaffdsdsadsafdds a dsf dsdfsads fdsads adsasa");
        }
        TIME_OFF("Element char* ctor");
    }

    {
        TIME_ON
        for (i = 0; i < 1000000; i += 1) {
            Atlas::Message::Element element;
            element =
                    "fdf adda ds dsafds asdfdasdsafdsdsaffdsdsadsafdds a dsf dsdfsads fdsads adsasa";
        }
        TIME_OFF("Element char* assign");
    }

    {
        TIME_ON
        for (i = 0; i < 1000000; i += 1.0) {
            MapType mapCopy = map;
            Atlas::Message::Element element(std::move(mapCopy));
        }
        TIME_OFF("Element move ctor");
    }

    {
        TIME_ON
        for (i = 0; i < 1000000; i += 1.0) {
            MapType mapCopy = map;
            Atlas::Message::Element element;
            element = std::move(mapCopy);
        }
        TIME_OFF("Element move assign");
    }

    {
        TIME_ON
        for (i = 0; i < 1000000; i += 1.0) {
            MapType mapCopy = map;
            Atlas::Message::Element element(mapCopy);
        }
        TIME_OFF("Element ctor");
    }

    {
        TIME_ON
        for (i = 0; i < 1000000; i += 1.0) {
            MapType mapCopy = map;
            Atlas::Message::Element element;
            element = mapCopy;
        }
        TIME_OFF("Element assign");
    }

    return 0;
}
<|endoftext|>


<commit_before>/***********************************************************************
 test/datetime.cpp - Tests the Date, DateTime, and Time classes.

 Copyright (c) 2007-2008 by Educational Technology Resources, Inc.
 Others may also hold copyrights on code in this file.  See the
 CREDITS file in the top directory of the distribution for details.

 This file is part of MySQL++.

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

 MySQL++ 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 MySQL++; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
 USA
***********************************************************************/

#include <mysql++.h>

#include <iostream>
#include <sstream>
#include <string>

#include <stdio.h>

using namespace mysqlpp;
using namespace std;

// Compare the given string against the object inserted into an ostream.
template <class T>
static unsigned int
test_ostream_insert(const T& object, const char* expected,
		const char* what)
{
	ostringstream os;
	os << object;
	if (os.str().compare(expected) == 0) {
		return 0;
	}
	else {
		cerr << what << " '" << object << "' should be '" <<
				expected << "' when inserted into ostream!" << endl;
		return 1;
	}
}

// Compare the given string against the return value of the object's
// str() method.
template <class T>
static unsigned int
test_str_method(const T& object, const char* expected, const char* what)
{
	if (object.str().compare(expected) == 0) {
		return 0;
	}
	else {
		cerr << what << " '" << object << "' should return '" <<
				expected << "' from str() method!" << endl;
		return 1;
	}
}

// Compare the given string against the object when cast to std::string
template <class T>
static unsigned int
test_string_operator(const T& object, const char* expected,
		const char* what)
{
	if (string(object).compare(expected) == 0) {
		return 0;
	}
	else {
		cerr << what << " '" << object << "' should be '" <<
				expected << "' when cast to std::string!" << endl;
		return 1;
	}
}

// Compare the given string against the object when converted in several
// different ways to a string.
template <class T>
static unsigned int
test_stringization(const T& object, const char* expected,
		const char* what)
{
	return	test_ostream_insert(object, expected, what) +
			test_string_operator(object, expected, what) +
			test_str_method(object, expected, what);
}

// Given a Date and a set of values we should expect to be in it,
// compare its outputs against values we compute separately.
static unsigned int
test_date(const Date& d, int year, int month, int day)
{
	if (	d.year() == year &&
			d.month() == month &&
			d.day() == day) {
		char ac[20];
		snprintf(ac, sizeof(ac), "%04d-%02d-%02d",
				year, month, day);
		return test_stringization(d, ac, "Date");
	}
	else {
		cerr << "Date '" << d << "' values should be '" <<
				year << '-' << month << '-' << day << endl;
		return 1;
	}
}

// Given a Time and a set of values we should expect to be in it,
// compare its outputs against values we compute separately.
static unsigned int
test_time(const Time& t, int hour, int minute, int second)
{
	if (	t.hour() == hour &&
			t.minute() == minute &&
			t.second() == second) {
		char ac[20];
		snprintf(ac, sizeof(ac), "%02d:%02d:%02d",
				hour, minute, second);
		return test_stringization(t, ac, "Time");
	}
	else {
		cerr << "Time '" << t << "' values should be '" <<
				hour << ':' << minute << ':' << second << endl;
		return 1;
	}
}

// Given a DateTime and a set of values we should expect to be in it,
// compare its outputs against values we compute separately.
static unsigned int
test_datetime(const DateTime& dt,
		int year, int month, int day,
		int hour, int minute, int second)
{
	return	test_date(Date(dt), year, month, day) +
			test_time(Time(dt), hour, minute, second);
}

// Run tests above for the various types we support using the date and
// time values given.
static unsigned int
test(int year, int month, int day, int hour, int minute, int second)
{
	unsigned int failures = 0;
	failures += test_date(Date(year, month, day), year, month, day);
	failures += test_datetime(
			DateTime(year, month, day, hour, minute, second),
			year, month, day, hour, minute, second);
	failures += test_time(Time(hour, minute, second), hour, minute,
			second);
	return failures;
}

int
main()
{
	unsigned int failures = 0;
	failures += test(0, 0, 0, 0, 0, 0);
	failures += test(1, 2, 3, 4, 5, 6);
	failures += test_stringization(DateTime(), "NOW()", "DateTime");
	DateTime dt;
	dt.year(2007);
	failures += test_stringization(dt, "2007-00-00 00:00:00", "DateTime");
	return failures;
}

<commit_msg>Added some verbosity to test/datetime.cpp.  Only useful for verifying visually that it does the right thing; no visible effect for end users.<commit_after>/***********************************************************************
 test/datetime.cpp - Tests the Date, DateTime, and Time classes.

 Copyright (c) 2007-2008 by Educational Technology Resources, Inc.
 Others may also hold copyrights on code in this file.  See the
 CREDITS file in the top directory of the distribution for details.

 This file is part of MySQL++.

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

 MySQL++ 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 MySQL++; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
 USA
***********************************************************************/

#include <mysql++.h>

#include <iostream>
#include <sstream>
#include <string>

#include <stdio.h>

using namespace mysqlpp;
using namespace std;

// Compare the given string against the object inserted into a Query stream.
template <class T>
static unsigned int
test_query_insert(const T& object, const char* expected,
		const char* what)
{
	Query q = Connection().query();	// don't do this in real code
	q << object;
	if (q.str().compare(expected) == 0) {
		cout << what << " is '" << expected <<
				"' in Query, as expected." << endl;
		return 0;
	}
	else {
		cerr << what << " '" << object << "' should be '" <<
				expected << "' when inserted into Query!" << endl;
		return 1;
	}
}

// Compare the given string against the object inserted into an ostream.
template <class T>
static unsigned int
test_ostream_insert(const T& object, const char* expected,
		const char* what)
{
	ostringstream os;
	os << object;
	if (os.str().compare(expected) == 0) {
		cout << what << " is '" << expected <<
				"' in ostream, as expected." << endl;
		return 0;
	}
	else {
		cerr << what << " '" << object << "' should be '" <<
				expected << "' when inserted into ostream!" << endl;
		return 1;
	}
}

// Compare the given string against the return value of the object's
// str() method.
template <class T>
static unsigned int
test_str_method(const T& object, const char* expected, const char* what)
{
	if (object.str().compare(expected) == 0) {
		cout << what << ".str() returns '" << expected <<
				"', as expected." << endl;
		return 0;
	}
	else {
		cerr << what << " '" << object << "' should return '" <<
				expected << "' from str() method!" << endl;
		return 1;
	}
}

// Compare the given string against the object when cast to std::string
template <class T>
static unsigned int
test_string_operator(const T& object, const char* expected,
		const char* what)
{
	if (string(object).compare(expected) == 0) {
		cout << "string(" << what << ") is '" << expected <<
				"', as expected." << endl;
		return 0;
	}
	else {
		cerr << what << " '" << object << "' should be '" <<
				expected << "' when cast to std::string!" << endl;
		return 1;
	}
}

// Compare the given string against the object when converted in several
// different ways to a string.
template <class T>
static unsigned int
test_stringization(const T& object, const char* expected,
		const char* what)
{
	return	test_query_insert(object, expected, what) +
			test_ostream_insert(object, expected, what) +
			test_string_operator(object, expected, what) +
			test_str_method(object, expected, what);
}

// Given a Date and a set of values we should expect to be in it,
// compare its outputs against values we compute separately.
static unsigned int
test_date(const Date& d, int year, int month, int day)
{
	if (	d.year() == year &&
			d.month() == month &&
			d.day() == day) {
		char ac[20];
		snprintf(ac, sizeof(ac), "%04d-%02d-%02d",
				year, month, day);
		return test_stringization(d, ac, "Date");
	}
	else {
		cerr << "Date '" << d << "' values should be '" <<
				year << '-' << month << '-' << day << endl;
		return 1;
	}
}

// Given a Time and a set of values we should expect to be in it,
// compare its outputs against values we compute separately.
static unsigned int
test_time(const Time& t, int hour, int minute, int second)
{
	if (	t.hour() == hour &&
			t.minute() == minute &&
			t.second() == second) {
		char ac[20];
		snprintf(ac, sizeof(ac), "%02d:%02d:%02d",
				hour, minute, second);
		return test_stringization(t, ac, "Time");
	}
	else {
		cerr << "Time '" << t << "' values should be '" <<
				hour << ':' << minute << ':' << second << endl;
		return 1;
	}
}

// Given a DateTime and a set of values we should expect to be in it,
// compare its outputs against values we compute separately.
static unsigned int
test_datetime(const DateTime& dt,
		int year, int month, int day,
		int hour, int minute, int second)
{
	return	test_date(Date(dt), year, month, day) +
			test_time(Time(dt), hour, minute, second);
}

// Run tests above for the various types we support using the date and
// time values given.
static unsigned int
test(int year, int month, int day, int hour, int minute, int second)
{
	unsigned int failures = 0;
	failures += test_date(Date(year, month, day), year, month, day);
	failures += test_datetime(
			DateTime(year, month, day, hour, minute, second),
			year, month, day, hour, minute, second);
	failures += test_time(Time(hour, minute, second), hour, minute,
			second);
	return failures;
}

int
main()
{
	unsigned int failures = 0;
	failures += test(0, 0, 0, 0, 0, 0);
	failures += test(1, 2, 3, 4, 5, 6);
	failures += test_stringization(DateTime(), "NOW()", "DateTime");
	DateTime dt;
	dt.year(2007);
	failures += test_stringization(dt, "2007-00-00 00:00:00", "DateTime");
	return failures;
}

<|endoftext|>


<commit_before>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "Copyright (c) 2012-2013 Tokutek Inc.  All rights reserved."
#ident "$Id$"

#include <stdio.h> // rename(),
#include <fcntl.h> // open()
#include <unistd.h> // close(), write(), read(), unlink(), truncate(), etc.
#include <sys/stat.h> // mkdir()
#include <errno.h>
#include <dlfcn.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>

#include "backup_internal.h"
#include "glassbox.h"
#include "manager.h"
#include "raii-malloc.h"
#include "real_syscalls.h"
#include "backup_debug.h"

#if DEBUG_HOTBACKUP
#define WARN(string, arg) HotBackup::InterposeWarn(string, arg);
#define TRACE(string, arg) HotBackup::InterposeTrace(string, arg);
#define ERROR(string, arg) HotBackup::InterposeError(string, arg);
#else
#define WARN(string,arg)
#define TRACE(string,arg)
#define ERROR(string,arg)
#endif

manager the_manager;

//***************************************
//
// Interposed public API:
//
//***************************************

///////////////////////////////////////////////////////////////////////////////
//
// open() -
//
// Description:
//
//     Either creates or opens a file in both the source directory
// and the backup directory.
//
extern "C" int open(const char* file, int oflag, ...) {
    int fd = 0;
    TRACE("open() intercepted, file = ", file);
    if (oflag & O_CREAT) {
        va_list ap;
        va_start(ap, oflag);
        mode_t mode = va_arg(ap, mode_t);
        va_end(ap);
        the_manager.lock_file_op();
        fd = call_real_open(file, oflag, mode);
        if (fd >= 0 && the_manager.is_alive()) {
            int ignore __attribute__((unused)) = the_manager.open(fd, file); // if there's an error in this call, it's been reported.  The application doesn't want to see the error.
        }

        the_manager.unlock_file_op();
    } else {
        fd = call_real_open(file, oflag);
        if (fd >= 0) {
            struct stat stats;
            int r = fstat(fd, &stats);
            if(r != 0) {
                goto out;
            }

            // TODO: What happens if we can't tell that the file is a FIFO?  Should we just the backup?  Skip this file?
            if (!S_ISFIFO(stats.st_mode) && the_manager.is_alive()) {
                int ignore __attribute__((unused)) = the_manager.open(fd, file); // if there's an error in the call, it's reported.  The application doesn't want to hear about it.
            }
        }
    }

out:
    return fd;
}

///////////////////////////////////////////////////////////////////////////////
//
// close() -
//
// Description:
//
//     Closes the file associated with the provided file descriptor
// in both the source and backup directories.
//
extern "C" int close(int fd) {
    int r = 0;
    TRACE("close() intercepted, fd = ", fd);
    if (the_manager.is_alive()) {
        the_manager.close(fd); // The application doesn't want to hear about problems. The backup manager has been notified.
    }

    r = call_real_close(fd);
    return r;
}

///////////////////////////////////////////////////////////////////////////////
//
// write() -
//
// Description:
//
//     Writes to the file associated with the given file descriptor
// in both the source and backup directories.
//
extern "C" ssize_t write(int fd, const void *buf, size_t nbyte) {
    TRACE("write() intercepted, fd = ", fd);

    ssize_t r = 0;
    if (the_manager.is_alive()) {
        // Moved the write down into manager where a lock can be obtained.
        r = the_manager.write(fd, buf, nbyte);
    } else {
        r = call_real_write(fd, buf, nbyte);
    }

    return r;
}

///////////////////////////////////////////////////////////////////////////////
//
// read() -
//
// Description:
//
//     Reads data into the given buffer from the source directory.
//
// Note:
//
//     The backup manager needs to know that the offset for the
// given file descriptor has changed, even though no bytes are
// read from the backup copy of the same file.
//
extern "C" ssize_t read(int fd, void *buf, size_t nbyte) {
    TRACE("read() intercepted, fd = ", fd);
    ssize_t r = 0;
    if (the_manager.is_alive()) {
        // Moved the read down into manager, where a lock can be obtained.
        r = the_manager.read(fd, buf, nbyte);
    } else {
        r = call_real_read(fd, buf, nbyte);
    }

    return r;
}

///////////////////////////////////////////////////////////////////////////////
//
// pwrite() -
//
// Description:
//
//     Writes to the file associated with the given file descriptor
// in both the source and backup directories.
//
extern "C" ssize_t pwrite(int fd, const void *buf, size_t nbyte, off_t offset) {
    TRACE("pwrite() intercepted, fd = ", fd);
    ssize_t r = 0;
    if (the_manager.is_alive()) {
        r = the_manager.pwrite(fd, buf, nbyte, offset);
    } else {
        r = call_real_pwrite(fd, buf, nbyte, offset);
    }

    return r;
}

///////////////////////////////////////////////////////////////////////////////
//
off_t lseek(int fd, off_t offset, int whence) {
    TRACE("lseek() intercepted fd =", fd);
    off_t r = 0;
    if (the_manager.is_alive()) {
        r = the_manager.lseek(fd, offset, whence);
    } else {
        r = call_real_lseek(fd, offset, whence);
    }

    return r;
}

///////////////////////////////////////////////////////////////////////////////
//
// ftruncate() -
//
// Description:
//
//     Deletes a portion of the file based on the given file descriptor.
//
extern "C" int ftruncate(int fd, off_t length) {
    TRACE("ftruncate() intercepted, fd = ", fd);
    int r = 0;
    if (the_manager.is_alive()) {
        r = the_manager.ftruncate(fd, length);
    } else {
        r = call_real_ftruncate(fd, length);
    }

    return r;
}

///////////////////////////////////////////////////////////////////////////////
//
// truncate() -
//
// Description:
//
//     Deletes a portion of the given file based on the given length.
//
extern "C" int truncate(const char *path, off_t length) {
    int r = 0;
    TRACE("truncate() intercepted, path = ", path);
    if (the_manager.is_alive()) {
        r = the_manager.truncate(path, length);
    } else {
        r = call_real_truncate(path, length);
    }

    return r;
}

///////////////////////////////////////////////////////////////////////////////
//
// unlink() -
//
// Description:
//
extern "C" int unlink(const char *path) {
    int r = 0;
    TRACE("unlink() intercepted, path = ", path);
    if (the_manager.is_alive()) {
        r = the_manager.unlink(path);
    } else {
        r = call_real_unlink(path);
    }
    return r;
}

///////////////////////////////////////////////////////////////////////////////
//
// rename() -
//
// Description:
//
extern "C" int rename(const char *oldpath, const char *newpath) {
    int r = 0;
    TRACE("rename() intercepted","");
    TRACE("-> oldpath = ", oldpath);
    TRACE("-> newpath = ", newpath);

    if (the_manager.is_alive()) {
        the_manager.lock_file_op();
        r = the_manager.rename(oldpath, newpath);
        the_manager.unlock_file_op();
    } else {
        r = call_real_rename(oldpath, newpath);
    }

    return r;
}

///////////////////////////////////////////////////////////////////////////////
//
// mkdir() -
//
// Description:
//
int mkdir(const char *pathname, mode_t mode) {
    int r = 0;
    TRACE("mkidr() intercepted", pathname);
    r = call_real_mkdir(pathname, mode);
    if (r == 0 && the_manager.is_alive()) {
        // Don't try to write if there was an error in the application.
        the_manager.mkdir(pathname);
    }
    return r;
}

extern "C" int tokubackup_create_backup(const char *source_dirs[], const char *dest_dirs[], int dir_count,
                                        backup_poll_fun_t poll_fun, void *poll_extra,
                                        backup_error_fun_t error_fun, void *error_extra) throw() {
    if (dir_count!=1) {
        error_fun(EINVAL, "Only one source directory may be specified for backup", error_extra);
        return EINVAL;
    }
    for (int i=0; i<dir_count; i++) {
        if (source_dirs[i]==NULL) {
            error_fun(EINVAL, "One of the source directories is NULL", error_extra);
            return EINVAL;
        }
        if (dest_dirs[i]==NULL) {
            error_fun(EINVAL, "One of the destination directories is NULL", error_extra);
            return EINVAL;
        }
        //int r = the_manager.add_directory(source_dirs[i], dest_dirs[i], poll_fun, poll_extra, error_fun, error_extra);
        //if (r!=0) return r;
    }

    // Check to make sure that the source and destination directories are
    // actually different.
    {
        with_object_to_free<char*> full_source (call_real_realpath(source_dirs[0], NULL));
        if (full_source.value == NULL) {
            error_fun(ENOENT, "Could not resolve source directory path.", error_extra);
            return ENOENT;
        }

        with_object_to_free<char*> full_destination(call_real_realpath(dest_dirs[0], NULL));
        if (full_destination.value == NULL) {
            error_fun(ENOENT, "Could not resolve destination directory path.", error_extra);
            return ENOENT;
        }

        if (strcmp(full_source.value, full_destination.value) == 0) {
            error_fun(EINVAL, "Source and destination directories are the same.", error_extra);
            return EINVAL;
        }
    }

    backup_callbacks calls(poll_fun, poll_extra, error_fun, error_extra, &get_throttle);
    return the_manager.do_backup(source_dirs[0], dest_dirs[0], &calls);
}

extern "C" void tokubackup_throttle_backup(unsigned long bytes_per_second) throw() {
    the_manager.set_throttle(bytes_per_second);
}

unsigned long get_throttle(void) throw() {
    return the_manager.get_throttle();
}

char *malloc_snprintf(size_t size, const char *format, ...) throw() {
    va_list ap;
    va_start(ap, format);
    char *result = (char*)malloc(size);
    vsnprintf(result, size, format, ap);
    va_end(ap);
    return result;
}

const char *tokubackup_version_string = "tokubackup 1.0 $Revision: 56100 $";

#ifdef GLASSBOX
void backup_pause_disable(bool b) throw() {
    the_manager.pause_disable(b);
}

void backup_set_keep_capturing(bool b) throw()
// Effect: see backup_internal.h
{
    the_manager.set_keep_capturing(b);
}
bool backup_is_capturing(void) throw() {
    return the_manager.is_capturing();
}
bool backup_done_copying(void) throw() {
    return the_manager.is_done_copying();
}
void backup_set_start_copying(bool b) throw() {
    the_manager.set_start_copying(b);
}
#endif
<commit_msg>fixes #28 Adding syscall-specific atomic lock around unlink.<commit_after>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "Copyright (c) 2012-2013 Tokutek Inc.  All rights reserved."
#ident "$Id$"

#include <stdio.h> // rename(),
#include <fcntl.h> // open()
#include <unistd.h> // close(), write(), read(), unlink(), truncate(), etc.
#include <sys/stat.h> // mkdir()
#include <errno.h>
#include <dlfcn.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>

#include "backup_internal.h"
#include "glassbox.h"
#include "manager.h"
#include "raii-malloc.h"
#include "real_syscalls.h"
#include "backup_debug.h"

#if DEBUG_HOTBACKUP
#define WARN(string, arg) HotBackup::InterposeWarn(string, arg);
#define TRACE(string, arg) HotBackup::InterposeTrace(string, arg);
#define ERROR(string, arg) HotBackup::InterposeError(string, arg);
#else
#define WARN(string,arg)
#define TRACE(string,arg)
#define ERROR(string,arg)
#endif

manager the_manager;

//***************************************
//
// Interposed public API:
//
//***************************************

///////////////////////////////////////////////////////////////////////////////
//
// open() -
//
// Description:
//
//     Either creates or opens a file in both the source directory
// and the backup directory.
//
extern "C" int open(const char* file, int oflag, ...) {
    int fd = 0;
    TRACE("open() intercepted, file = ", file);
    if (oflag & O_CREAT) {
        va_list ap;
        va_start(ap, oflag);
        mode_t mode = va_arg(ap, mode_t);
        va_end(ap);
        the_manager.lock_file_op();
        fd = call_real_open(file, oflag, mode);
        if (fd >= 0 && the_manager.is_alive()) {
            int ignore __attribute__((unused)) = the_manager.open(fd, file); // if there's an error in this call, it's been reported.  The application doesn't want to see the error.
        }

        the_manager.unlock_file_op();
    } else {
        fd = call_real_open(file, oflag);
        if (fd >= 0) {
            struct stat stats;
            int r = fstat(fd, &stats);
            if(r != 0) {
                goto out;
            }

            // TODO: What happens if we can't tell that the file is a FIFO?  Should we just the backup?  Skip this file?
            if (!S_ISFIFO(stats.st_mode) && the_manager.is_alive()) {
                int ignore __attribute__((unused)) = the_manager.open(fd, file); // if there's an error in the call, it's reported.  The application doesn't want to hear about it.
            }
        }
    }

out:
    return fd;
}

///////////////////////////////////////////////////////////////////////////////
//
// close() -
//
// Description:
//
//     Closes the file associated with the provided file descriptor
// in both the source and backup directories.
//
extern "C" int close(int fd) {
    int r = 0;
    TRACE("close() intercepted, fd = ", fd);
    if (the_manager.is_alive()) {
        the_manager.close(fd); // The application doesn't want to hear about problems. The backup manager has been notified.
    }

    r = call_real_close(fd);
    return r;
}

///////////////////////////////////////////////////////////////////////////////
//
// write() -
//
// Description:
//
//     Writes to the file associated with the given file descriptor
// in both the source and backup directories.
//
extern "C" ssize_t write(int fd, const void *buf, size_t nbyte) {
    TRACE("write() intercepted, fd = ", fd);

    ssize_t r = 0;
    if (the_manager.is_alive()) {
        // Moved the write down into manager where a lock can be obtained.
        r = the_manager.write(fd, buf, nbyte);
    } else {
        r = call_real_write(fd, buf, nbyte);
    }

    return r;
}

///////////////////////////////////////////////////////////////////////////////
//
// read() -
//
// Description:
//
//     Reads data into the given buffer from the source directory.
//
// Note:
//
//     The backup manager needs to know that the offset for the
// given file descriptor has changed, even though no bytes are
// read from the backup copy of the same file.
//
extern "C" ssize_t read(int fd, void *buf, size_t nbyte) {
    TRACE("read() intercepted, fd = ", fd);
    ssize_t r = 0;
    if (the_manager.is_alive()) {
        // Moved the read down into manager, where a lock can be obtained.
        r = the_manager.read(fd, buf, nbyte);
    } else {
        r = call_real_read(fd, buf, nbyte);
    }

    return r;
}

///////////////////////////////////////////////////////////////////////////////
//
// pwrite() -
//
// Description:
//
//     Writes to the file associated with the given file descriptor
// in both the source and backup directories.
//
extern "C" ssize_t pwrite(int fd, const void *buf, size_t nbyte, off_t offset) {
    TRACE("pwrite() intercepted, fd = ", fd);
    ssize_t r = 0;
    if (the_manager.is_alive()) {
        r = the_manager.pwrite(fd, buf, nbyte, offset);
    } else {
        r = call_real_pwrite(fd, buf, nbyte, offset);
    }

    return r;
}

///////////////////////////////////////////////////////////////////////////////
//
off_t lseek(int fd, off_t offset, int whence) {
    TRACE("lseek() intercepted fd =", fd);
    off_t r = 0;
    if (the_manager.is_alive()) {
        r = the_manager.lseek(fd, offset, whence);
    } else {
        r = call_real_lseek(fd, offset, whence);
    }

    return r;
}

///////////////////////////////////////////////////////////////////////////////
//
// ftruncate() -
//
// Description:
//
//     Deletes a portion of the file based on the given file descriptor.
//
extern "C" int ftruncate(int fd, off_t length) {
    TRACE("ftruncate() intercepted, fd = ", fd);
    int r = 0;
    if (the_manager.is_alive()) {
        r = the_manager.ftruncate(fd, length);
    } else {
        r = call_real_ftruncate(fd, length);
    }

    return r;
}

///////////////////////////////////////////////////////////////////////////////
//
// truncate() -
//
// Description:
//
//     Deletes a portion of the given file based on the given length.
//
extern "C" int truncate(const char *path, off_t length) {
    int r = 0;
    TRACE("truncate() intercepted, path = ", path);
    if (the_manager.is_alive()) {
        r = the_manager.truncate(path, length);
    } else {
        r = call_real_truncate(path, length);
    }

    return r;
}

///////////////////////////////////////////////////////////////////////////////
//
// unlink() -
//
// Description:
//
extern "C" int unlink(const char *path) {
    int r = 0;
    TRACE("unlink() intercepted, path = ", path);
    if (the_manager.is_alive()) {
        the_manager.lock_file_op();
        r = the_manager.unlink(path);
        the_manager.unlock_file_op();
    } else {
        r = call_real_unlink(path);
    }
    return r;
}

///////////////////////////////////////////////////////////////////////////////
//
// rename() -
//
// Description:
//
extern "C" int rename(const char *oldpath, const char *newpath) {
    int r = 0;
    TRACE("rename() intercepted","");
    TRACE("-> oldpath = ", oldpath);
    TRACE("-> newpath = ", newpath);

    if (the_manager.is_alive()) {
        the_manager.lock_file_op();
        r = the_manager.rename(oldpath, newpath);
        the_manager.unlock_file_op();
    } else {
        r = call_real_rename(oldpath, newpath);
    }

    return r;
}

///////////////////////////////////////////////////////////////////////////////
//
// mkdir() -
//
// Description:
//
int mkdir(const char *pathname, mode_t mode) {
    int r = 0;
    TRACE("mkidr() intercepted", pathname);
    r = call_real_mkdir(pathname, mode);
    if (r == 0 && the_manager.is_alive()) {
        // Don't try to write if there was an error in the application.
        the_manager.mkdir(pathname);
    }
    return r;
}

extern "C" int tokubackup_create_backup(const char *source_dirs[], const char *dest_dirs[], int dir_count,
                                        backup_poll_fun_t poll_fun, void *poll_extra,
                                        backup_error_fun_t error_fun, void *error_extra) throw() {
    if (dir_count!=1) {
        error_fun(EINVAL, "Only one source directory may be specified for backup", error_extra);
        return EINVAL;
    }
    for (int i=0; i<dir_count; i++) {
        if (source_dirs[i]==NULL) {
            error_fun(EINVAL, "One of the source directories is NULL", error_extra);
            return EINVAL;
        }
        if (dest_dirs[i]==NULL) {
            error_fun(EINVAL, "One of the destination directories is NULL", error_extra);
            return EINVAL;
        }
        //int r = the_manager.add_directory(source_dirs[i], dest_dirs[i], poll_fun, poll_extra, error_fun, error_extra);
        //if (r!=0) return r;
    }

    // Check to make sure that the source and destination directories are
    // actually different.
    {
        with_object_to_free<char*> full_source (call_real_realpath(source_dirs[0], NULL));
        if (full_source.value == NULL) {
            error_fun(ENOENT, "Could not resolve source directory path.", error_extra);
            return ENOENT;
        }

        with_object_to_free<char*> full_destination(call_real_realpath(dest_dirs[0], NULL));
        if (full_destination.value == NULL) {
            error_fun(ENOENT, "Could not resolve destination directory path.", error_extra);
            return ENOENT;
        }

        if (strcmp(full_source.value, full_destination.value) == 0) {
            error_fun(EINVAL, "Source and destination directories are the same.", error_extra);
            return EINVAL;
        }
    }

    backup_callbacks calls(poll_fun, poll_extra, error_fun, error_extra, &get_throttle);
    return the_manager.do_backup(source_dirs[0], dest_dirs[0], &calls);
}

extern "C" void tokubackup_throttle_backup(unsigned long bytes_per_second) throw() {
    the_manager.set_throttle(bytes_per_second);
}

unsigned long get_throttle(void) throw() {
    return the_manager.get_throttle();
}

char *malloc_snprintf(size_t size, const char *format, ...) throw() {
    va_list ap;
    va_start(ap, format);
    char *result = (char*)malloc(size);
    vsnprintf(result, size, format, ap);
    va_end(ap);
    return result;
}

const char *tokubackup_version_string = "tokubackup 1.0 $Revision: 56100 $";

#ifdef GLASSBOX
void backup_pause_disable(bool b) throw() {
    the_manager.pause_disable(b);
}

void backup_set_keep_capturing(bool b) throw()
// Effect: see backup_internal.h
{
    the_manager.set_keep_capturing(b);
}
bool backup_is_capturing(void) throw() {
    return the_manager.is_capturing();
}
bool backup_done_copying(void) throw() {
    return the_manager.is_done_copying();
}
void backup_set_start_copying(bool b) throw() {
    the_manager.set_start_copying(b);
}
#endif
<|endoftext|>


<commit_before>/*   _____
 * /\  _  \                     __
 * \ \ \_\ \      __    __  __ /\_\
 *  \ \  __ \   /'_ `\ /\ \/\ \\/\ \
 *   \ \ \/\ \ /\ \_\ \\ \ \_\ \\ \ \
 *    \ \_\ \_\\ \____ \\ \____/ \ \_\
 *     \/_/\/_/ \/____\ \\/___/   \/_/
 *                /\____/
 *                \_/__/
 *
 * Copyright (c) 2011 Joshua Larouche
 *
 *
 * License: (BSD)
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name of Agui nor the names of its contributors may
 *    be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef AGUI_TABLE_LAYOUT_HPP
#define AGUI_TABLE_LAYOUT_HPP

#include "Agui/Layout.hpp"
namespace agui
{
	/**
     * Allows to layout widgets in table, row/column dimenensions are dependent on the
     * size of the biggest widget in the corresponding row/column, as in HTML table.
     * Items in the cell have vertical centering.
     * @TODO rowspan/cellspan
     * @TODO Specify align for individual cells/rows/columns
     * @author Michal Kovarik
     * @since 0.1.0
     */
	class TableLayout :
		public Layout
	{
		int rows;
		int columns;
		int horizontalSpacing;
		int verticalSpacing;
	protected:
	/**
     * Lays out the children in a grid.
     * @since 0.1.0
     */
		virtual void layoutChildren();
	public:
	/**
     * Sets the number of rows expected to have.
	 *
	 * This can be set to zero if you do not know however
	 * either number of rows or number of columns must be non zero.
	 * They cannot both be zero.
     * @since 0.1.0
     */
		virtual void setNumberOfRows(int rows);
	/**
     * Sets the number of columns expected to have.
	 *
	 * This can be set to zero if you do not know however
	 * either number of rows or number of columns must be non zero.
	 * They cannot both be zero.
     * @since 0.1.0
     */
		virtual void setNumberOfColumns(int columns);
		/**
	 * Sets the horizontal spacing between each widget. The first widget in the row receives no spacing.
	 * Use the margins for this.
     * @since 0.1.0
     */
		virtual void setHorizontalSpacing(int spacing);
	/**
	 * Sets the vertical spacing between each widget. The first widget in the column receives no spacing.
	 * Use the margins for this.
     * @since 0.1.0
     */
		virtual void setVerticalSpacing(int spacing);
	/**
	 * @return The number of rows in the grid or zero if unknown.
     * @since 0.1.0
     */
		virtual int getNumberOfRows() const;
	/**
	 * @return The number of columns in the grid or zero if unknown.
     * @since 0.1.0
     */
		virtual int getNumberOfColumns() const;
			/**
	 * @return The horizontal spacing between widgets.
     * @since 0.1.0
     */
		virtual int getHorizontalSpacing() const;
	/**
	 * @return The vertical spacing between widgets.
     * @since 0.1.0
     */
		virtual int getVerticalSpacing() const;
    virtual void resizeToContents();
	/**
	 * Default constructor.
     * @since 0.1.0
     */
		TableLayout(void);
		/**
	 * Default destructor.
     * @since 0.1.0
     */
		virtual ~TableLayout(void);
	};
}
#endif
<commit_msg>Typo fix<commit_after>/*   _____
 * /\  _  \                     __
 * \ \ \_\ \      __    __  __ /\_\
 *  \ \  __ \   /'_ `\ /\ \/\ \\/\ \
 *   \ \ \/\ \ /\ \_\ \\ \ \_\ \\ \ \
 *    \ \_\ \_\\ \____ \\ \____/ \ \_\
 *     \/_/\/_/ \/____\ \\/___/   \/_/
 *                /\____/
 *                \_/__/
 *
 * Copyright (c) 2011 Joshua Larouche
 *
 *
 * License: (BSD)
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name of Agui nor the names of its contributors may
 *    be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef AGUI_TABLE_LAYOUT_HPP
#define AGUI_TABLE_LAYOUT_HPP

#include "Agui/Layout.hpp"
namespace agui
{
	/**
     * Allows to layout widgets in table, row/column dimenensions are dependent on the
     * size of the biggest widget in the corresponding row/column, as in HTML table.
     * Items in the cell have vertical centering.
     * @TODO rowspan/colspan
     * @TODO Specify align for individual cells/rows/columns
     * @author Michal Kovarik
     * @since 0.1.0
     */
	class TableLayout :
		public Layout
	{
		int rows;
		int columns;
		int horizontalSpacing;
		int verticalSpacing;
	protected:
	/**
     * Lays out the children in a grid.
     * @since 0.1.0
     */
		virtual void layoutChildren();
	public:
	/**
     * Sets the number of rows expected to have.
	 *
	 * This can be set to zero if you do not know however
	 * either number of rows or number of columns must be non zero.
	 * They cannot both be zero.
     * @since 0.1.0
     */
		virtual void setNumberOfRows(int rows);
	/**
     * Sets the number of columns expected to have.
	 *
	 * This can be set to zero if you do not know however
	 * either number of rows or number of columns must be non zero.
	 * They cannot both be zero.
     * @since 0.1.0
     */
		virtual void setNumberOfColumns(int columns);
		/**
	 * Sets the horizontal spacing between each widget. The first widget in the row receives no spacing.
	 * Use the margins for this.
     * @since 0.1.0
     */
		virtual void setHorizontalSpacing(int spacing);
	/**
	 * Sets the vertical spacing between each widget. The first widget in the column receives no spacing.
	 * Use the margins for this.
     * @since 0.1.0
     */
		virtual void setVerticalSpacing(int spacing);
	/**
	 * @return The number of rows in the grid or zero if unknown.
     * @since 0.1.0
     */
		virtual int getNumberOfRows() const;
	/**
	 * @return The number of columns in the grid or zero if unknown.
     * @since 0.1.0
     */
		virtual int getNumberOfColumns() const;
			/**
	 * @return The horizontal spacing between widgets.
     * @since 0.1.0
     */
		virtual int getHorizontalSpacing() const;
	/**
	 * @return The vertical spacing between widgets.
     * @since 0.1.0
     */
		virtual int getVerticalSpacing() const;
    virtual void resizeToContents();
	/**
	 * Default constructor.
     * @since 0.1.0
     */
		TableLayout(void);
		/**
	 * Default destructor.
     * @since 0.1.0
     */
		virtual ~TableLayout(void);
	};
}
#endif
<|endoftext|>


<commit_before>#ifndef JEZUK_DOM_EXCEPTION_H
#define JEZUK_DOM_EXCEPTION_H

////////////////////////////
// C++ DOM definition
////////////////////////////

#include <stdexcept>
#include <typeinfo>

namespace Arabica
{
namespace DOM
{

class DOMBadCast : public std::bad_cast
{
public:
  DOMBadCast(const char* expectedType) :
      message_(std::string("Cannot cast to ") + std::string(expectedType))
  {
  } // DOMBadCast

  DOMBadCast(const DOMBadCast& rhs) :
      message_(rhs.message_)
  {
  } // DOMBadCase

  virtual ~DOMBadCast() throw()
  {
  } // DOMBadCast

  virtual const char* what() const throw()
  {
    return message_.c_str();
  } // what

private:
  const std::string message_;

  DOMBadCast& operator=(const DOMBadCast&);
  bool operator==(const DOMBadCast&) const;
}; // DOMBadCast

class DOMException : public std::runtime_error
{
public:
  enum CODE
  {
    INDEX_SIZE_ERR = 1,
    DOMSTRING_SIZE_ERR = 2,
    HIERARCHY_REQUEST_ERR = 3,
    WRONG_DOCUMENT_ERR = 4,
    INVALID_CHARACTER_ERR = 5,
    NO_DATA_ALLOWED_ERR = 6,
    NO_MODIFICATION_ALLOWED_ERR = 7,
    NOT_FOUND_ERR = 8,
    NOT_SUPPORTED_ERR = 9 ,
    INUSE_ATTRIBUTE_ERR = 10,
    INVALID_STATE_ERR,
    SYNTAX_ERR,
    INVALID_MODIFICATION_ERR,
    NAMESPACE_ERR,
    INVALID_ACCESS_ERR
  }; // enum CODE

  DOMException(CODE code) :
    std::runtime_error("DOMException"),
    code_(code)
  {
  } // DOMException

  DOMException(const DOMException& rhs) :
    std::runtime_error(rhs),
    code_(rhs.code_)
  {
  } // DOMException

  virtual ~DOMException() throw()
  {
  } // DOMBadCast

  CODE code() const { return code_; }

  virtual const char* what() const throw()
  {
    switch(code_)
    {
      case INDEX_SIZE_ERR:
        return "Index size error";
      case DOMSTRING_SIZE_ERR:
        return "DOMString size error";
      case HIERARCHY_REQUEST_ERR:
        return "Hierarchy request error";
      case WRONG_DOCUMENT_ERR:
        return "Wrong Document error";
      case INVALID_CHARACTER_ERR:
        return "Invalid Character error";
      case NO_DATA_ALLOWED_ERR:
        return "No data allowed error";
      case NO_MODIFICATION_ALLOWED_ERR:
        return "No modification allowed error";
      case NOT_FOUND_ERR:
        return "Not found error";
      case NOT_SUPPORTED_ERR:
        return "Not supported error";
      case INUSE_ATTRIBUTE_ERR:
        return "Attribute inuse error";
      case INVALID_STATE_ERR:
        return "Invalid state";
      case SYNTAX_ERR:
        return "Syntax error";
      case INVALID_MODIFICATION_ERR:
        return "Invalid modification error";
      case NAMESPACE_ERR:
        return "Namespace error";
      case INVALID_ACCESS_ERR:
        return "Invalid access error";
    } // switch(code_)

    return "DOM error";
  } // what

private:
  DOMBadCast& operator=(const DOMBadCast&);
  bool operator==(const DOMBadCast&) const;

  CODE code_;
}; // class DOMException

} // namespace DOM
} // namespace Arabica

#endif

<commit_msg>Reverted last commit<commit_after>#ifndef JEZUK_DOM_EXCEPTION_H
#define JEZUK_DOM_EXCEPTION_H

////////////////////////////
// C++ DOM definition
////////////////////////////

#include <stdexcept>
#include <typeinfo>

namespace Arabica
{
namespace DOM
{

class DOMBadCast : public std::bad_cast
{
public:
  DOMBadCast(const char* expectedType) :
      message_(std::string("Cannot cast to ") + expectedType)
  {
  } // DOMBadCast

  DOMBadCast(const DOMBadCast& rhs) :
      message_(rhs.message_)
  {
  } // DOMBadCase

  virtual ~DOMBadCast() throw()
  {
  } // DOMBadCast

  virtual const char* what() const throw()
  {
    return message_.c_str();
  } // what

private:
  const std::string message_;

  DOMBadCast& operator=(const DOMBadCast&);
  bool operator==(const DOMBadCast&) const;
}; // DOMBadCast

class DOMException : public std::runtime_error
{
public:
  enum CODE
  {
    INDEX_SIZE_ERR = 1,
    DOMSTRING_SIZE_ERR = 2,
    HIERARCHY_REQUEST_ERR = 3,
    WRONG_DOCUMENT_ERR = 4,
    INVALID_CHARACTER_ERR = 5,
    NO_DATA_ALLOWED_ERR = 6,
    NO_MODIFICATION_ALLOWED_ERR = 7,
    NOT_FOUND_ERR = 8,
    NOT_SUPPORTED_ERR = 9 ,
    INUSE_ATTRIBUTE_ERR = 10,
    INVALID_STATE_ERR,
    SYNTAX_ERR,
    INVALID_MODIFICATION_ERR,
    NAMESPACE_ERR,
    INVALID_ACCESS_ERR
  }; // enum CODE

  DOMException(CODE code) :
    std::runtime_error("DOMException"),
    code_(code)
  {
  } // DOMException

  DOMException(const DOMException& rhs) :
    std::runtime_error(rhs),
    code_(rhs.code_)
  {
  } // DOMException

  virtual ~DOMException() throw()
  {
  } // DOMBadCast

  CODE code() const { return code_; }

  virtual const char* what() const throw()
  {
    switch(code_)
    {
      case INDEX_SIZE_ERR:
        return "Index size error";
      case DOMSTRING_SIZE_ERR:
        return "DOMString size error";
      case HIERARCHY_REQUEST_ERR:
        return "Hierarchy request error";
      case WRONG_DOCUMENT_ERR:
        return "Wrong Document error";
      case INVALID_CHARACTER_ERR:
        return "Invalid Character error";
      case NO_DATA_ALLOWED_ERR:
        return "No data allowed error";
      case NO_MODIFICATION_ALLOWED_ERR:
        return "No modification allowed error";
      case NOT_FOUND_ERR:
        return "Not found error";
      case NOT_SUPPORTED_ERR:
        return "Not supported error";
      case INUSE_ATTRIBUTE_ERR:
        return "Attribute inuse error";
      case INVALID_STATE_ERR:
        return "Invalid state";
      case SYNTAX_ERR:
        return "Syntax error";
      case INVALID_MODIFICATION_ERR:
        return "Invalid modification error";
      case NAMESPACE_ERR:
        return "Namespace error";
      case INVALID_ACCESS_ERR:
        return "Invalid access error";
    } // switch(code_)

    return "DOM error";
  } // what

private:
  DOMBadCast& operator=(const DOMBadCast&);
  bool operator==(const DOMBadCast&) const;

  CODE code_;
}; // class DOMException

} // namespace DOM
} // namespace Arabica

#endif

<|endoftext|>


<commit_before>/* ***************************************************************************
 * LCUI_Widget.hpp -- C++ class for GUI widget
 *
 * Copyright (C) 2013 by
 * Liu Chao
 *
 * This file is part of the LCUI project, and may only be used, modified, and
 * distributed under the terms of the GPLv2.
 *
 * (GPLv2 is abbreviation of GNU General Public License Version 2)
 *
 * By continuing to use, modify, or distribute this file you indicate that you
 * have read the license and understand and accept it fully.
 *
 * The LCUI project 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 GPL v2 for more details.
 *
 * You should have received a copy of the GPLv2 along with this file. It is
 * usually in the LICENSE.TXT file, If not, see <http://www.gnu.org/licenses/>.
 * ****************************************************************************/

/* ****************************************************************************
 * LCUI_Widget.hp -- GUIC++
 *
 * Ȩ (C) 2013
 *
 *
 * ļLCUIĿһֻ֣ԸGPLv2Эʹáĺͷ
 *
 * (GPLv2  GNUͨù֤ڶ Ӣд)
 *
 * ʹá޸Ļ򷢲ļѾĶȫͽЭ顣
 *
 * LCUI ĿǻʹĿĶɢģκεΣûԻ
 * ;GPLv2Э顣
 *
 * ӦյڱļGPLv2ЭĸͨLICENSE.TXTļУ
 * ûУ鿴<http://www.gnu.org/licenses/>.
 * ****************************************************************************/

#ifndef __LCUI_WIDGET_HPP__
#define __LCUI_WIDGET_HPP__

#ifdef __cplusplus
class LCUIWidget {
public:
	LCUIWidget( const char* widget_type );
	~LCUIWidget(void);

	LCUI_Widget *getWidget( void );
	LCUI_Size getSize( void );
	int getHeight( void );
	int getWidth( void );
	LCUI_Rect getRect( void );
	LCUI_Pos getPos( void );
	void *getPrivateData( void );
	int addInvalidArea( LCUI_Rect );
	int addInvalidArea( int, int, int, int );
	void show( LCUI_BOOL );
	void enable( LCUI_BOOL );
	void modal( LCUI_BOOL );
	void move( LCUI_Pos );
	void move( int , int );
	void resize( LCUI_Size );
	void resize( int, int );
	void dock( DOCK_TYPE );
	void update( LCUI_BOOL );
	void addChild( LCUI_Widget * );
	void addChild( LCUIWidget & );
	void getGraph( LCUI_Graph *, LCUI_Rect );
	LCUI_Graph* getSelfGraph( void );
	void syncInvalidArea( void );
	void setAlpha( unsigned char );
	void setPadding( int, int, int, int );
	void setPadding( int , int );
	void setPadding( int all );
	void setBorder( unsigned int, BORDER_STYLE, LCUI_RGB );
	void setBorderRadius( unsigned int );
	void setAlign( ALIGN_TYPE , LCUI_Pos );
	void setBackgroundImage( LCUI_Graph * );
	void setBackgroundLayout( LAYOUT_TYPE );
	void setBackgroundColor( LCUI_RGB );
	void setBackgroundTransparent( LCUI_BOOL );
	void destroy( void );
protected:
	LCUI_Widget *widget;
};

LCUIWidget::LCUIWidget( const char *widget_type )
{
	widget = Widget_New( widget_type );
}

LCUIWidget::~LCUIWidget(void)
{
	Widget_Destroy( widget );
}

LCUI_Widget *LCUIWidget::getWidget( void )
{
	return widget;
}

LCUI_Size LCUIWidget::getSize( void )
{
	return Widget_GetSize( widget );
}

int LCUIWidget::getHeight( void )
{
	return Widget_GetHeight( widget );
}

int LCUIWidget::getWidth( void )
{
	return Widget_GetWidth( widget );
}

LCUI_Rect LCUIWidget::getRect( void )
{
	return Widget_GetRect( widget );
}

LCUI_Pos LCUIWidget::getPos( void )
{
	return Widget_GetPos( widget );
}

void *LCUIWidget::getPrivateData( void )
{
	return Widget_GetPrivData( widget );
}

int LCUIWidget::addInvalidArea( LCUI_Rect area )
{
	return Widget_InvalidArea( widget, area );
}

int LCUIWidget::addInvalidArea( int x, int y, int w, int h )
{
	return Widget_InvalidArea( widget, Rect(x, y, w, h) );
}

void LCUIWidget::show( LCUI_BOOL need_show = TRUE )
{
	if(need_show) {
		Widget_Show( widget );
	} else {
		Widget_Hide( widget );
	}
}

void LCUIWidget::modal( LCUI_BOOL is_modal = TRUE )
{
	Widget_SetModal( widget, is_modal );
}

void LCUIWidget::dock( DOCK_TYPE dock_type )
{
	Widget_SetDock( widget, dock_type );
}

void LCUIWidget::move( LCUI_Pos new_pos )
{
	Widget_Move( widget, new_pos );
}

void LCUIWidget::move( int x, int y )
{
	Widget_Move( widget, Pos(x,y) );
}

void LCUIWidget::resize( LCUI_Size new_size )
{
	Widget_Resize( widget, new_size );
}

void LCUIWidget::resize( int w, int h )
{
	Widget_Resize( widget, Size(w,h) );
}

void LCUIWidget::update( LCUI_BOOL keep_new = FALSE )
{
	if( keep_new ) {
		Widget_Update( widget );
	} else {
		__Widget_Update( widget );
	}
}

void LCUIWidget::addChild( LCUI_Widget *child_widget )
{
	Widget_Container_Add( widget, child_widget );
}

void LCUIWidget::addChild( LCUIWidget &child_widget )
{
	Widget_Container_Add( widget, child_widget.getWidget() );
}

void LCUIWidget::getGraph( LCUI_Graph *graph_buff, LCUI_Rect rect )
{
	Widget_GetGraph( widget, graph_buff, rect );
}

LCUI_Graph* LCUIWidget::getSelfGraph( void )
{
	return Widget_GetSelfGraph( widget );
}

void LCUIWidget::syncInvalidArea( void )
{
	Widget_SyncInvalidArea( widget );
}

void LCUIWidget::setAlpha( unsigned char alpha )
{
	Widget_SetAlpha( widget, alpha );
}

void LCUIWidget::setPadding( int top, int bottom, int left, int right )
{
	Widget_SetPadding( widget, Padding(top, bottom, left, right) );
}

void LCUIWidget::setPadding( int top_bottom, int left_right )
{
	Widget_SetPadding( widget, Padding(top_bottom, top_bottom, left_right, left_right) );
}

void LCUIWidget::setPadding( int all )
{
	Widget_SetPadding( widget, Padding(all, all, all, all) );
}

void LCUIWidget::setBorder( unsigned int width_px, BORDER_STYLE style, LCUI_RGB color )
{
	Widget_SetBorder( widget, Border(width_px, style, color) );
}

void LCUIWidget::setBorderRadius( unsigned int radius )
{
	Widget_SetBorderRadius( widget, radius );
}

void LCUIWidget::setAlign( ALIGN_TYPE align, LCUI_Pos offset = Pos(0,0) )
{
	Widget_SetAlign( widget, align, offset );
}

void LCUIWidget::setBackgroundImage( LCUI_Graph *img )
{
	Widget_SetBackgroundImage( widget, img );
}

void LCUIWidget::setBackgroundLayout( LAYOUT_TYPE layout )
{
	Widget_SetBackgroundLayout( widget, layout );
}

void LCUIWidget::setBackgroundColor( LCUI_RGB color )
{
	Widget_SetBackgroundColor( widget, color );
}

void LCUIWidget::setBackgroundTransparent( LCUI_BOOL flag = TRUE )
{
	Widget_SetBackgroundTransparent( widget, flag );
}

void LCUIWidget::destroy( void )
{
	Widget_Destroy( widget );
}
#endif

#endif
<commit_msg>修改LCUI_Widget.hpp文件编码<commit_after>/* ***************************************************************************
 * LCUI_Widget.hpp -- C++ class for GUI widget
 *
 * Copyright (C) 2013 by
 * Liu Chao
 *
 * This file is part of the LCUI project, and may only be used, modified, and
 * distributed under the terms of the GPLv2.
 *
 * (GPLv2 is abbreviation of GNU General Public License Version 2)
 *
 * By continuing to use, modify, or distribute this file you indicate that you
 * have read the license and understand and accept it fully.
 *
 * The LCUI project 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 GPL v2 for more details.
 *
 * You should have received a copy of the GPLv2 along with this file. It is
 * usually in the LICENSE.TXT file, If not, see <http://www.gnu.org/licenses/>.
 * ****************************************************************************/

/* ****************************************************************************
 * LCUI_Widget.hpp -- GUI部件的C++类
 *
 * 版权所有 (C) 2013 归属于
 * 刘超
 *
 * 这个文件是LCUI项目的一部分，并且只可以根据GPLv2许可协议来使用、更改和发布。
 *
 * (GPLv2 是 GNU通用公共许可证第二版 的英文缩写)
 *
 * 继续使用、修改或发布本文件，表明您已经阅读并完全理解和接受这个许可协议。
 *
 * LCUI 项目是基于使用目的而加以散布的，但不负任何担保责任，甚至没有适销性或特
 * 定用途的隐含担保，详情请参照GPLv2许可协议。
 *
 * 您应已收到附随于本文件的GPLv2许可协议的副本，它通常在LICENSE.TXT文件中，如果
 * 没有，请查看：<http://www.gnu.org/licenses/>.
 * ****************************************************************************/

#ifndef __LCUI_WIDGET_HPP__
#define __LCUI_WIDGET_HPP__

#ifdef __cplusplus
class LCUIWidget {
public:
	LCUIWidget( const char* widget_type );
	~LCUIWidget(void);

	LCUI_Widget *getWidget( void );
	LCUI_Size getSize( void );
	int getHeight( void );
	int getWidth( void );
	LCUI_Rect getRect( void );
	LCUI_Pos getPos( void );
	void *getPrivateData( void );
	int addInvalidArea( LCUI_Rect );
	int addInvalidArea( int, int, int, int );
	void show( LCUI_BOOL );
	void enable( LCUI_BOOL );
	void modal( LCUI_BOOL );
	void move( LCUI_Pos );
	void move( int , int );
	void resize( LCUI_Size );
	void resize( int, int );
	void dock( DOCK_TYPE );
	void update( LCUI_BOOL );
	void addChild( LCUI_Widget * );
	void addChild( LCUIWidget & );
	void getGraph( LCUI_Graph *, LCUI_Rect );
	LCUI_Graph* getSelfGraph( void );
	void syncInvalidArea( void );
	void setAlpha( unsigned char );
	void setPadding( int, int, int, int );
	void setPadding( int , int );
	void setPadding( int all );
	void setBorder( unsigned int, BORDER_STYLE, LCUI_RGB );
	void setBorderRadius( unsigned int );
	void setAlign( ALIGN_TYPE , LCUI_Pos );
	void setBackgroundImage( LCUI_Graph * );
	void setBackgroundLayout( LAYOUT_TYPE );
	void setBackgroundColor( LCUI_RGB );
	void setBackgroundTransparent( LCUI_BOOL );
	void destroy( void );
protected:
	LCUI_Widget *widget;
};

LCUIWidget::LCUIWidget( const char *widget_type )
{
	widget = Widget_New( widget_type );
}

LCUIWidget::~LCUIWidget(void)
{
	Widget_Destroy( widget );
}

LCUI_Widget *LCUIWidget::getWidget( void )
{
	return widget;
}

LCUI_Size LCUIWidget::getSize( void )
{
	return Widget_GetSize( widget );
}

int LCUIWidget::getHeight( void )
{
	return Widget_GetHeight( widget );
}

int LCUIWidget::getWidth( void )
{
	return Widget_GetWidth( widget );
}

LCUI_Rect LCUIWidget::getRect( void )
{
	return Widget_GetRect( widget );
}

LCUI_Pos LCUIWidget::getPos( void )
{
	return Widget_GetPos( widget );
}

void *LCUIWidget::getPrivateData( void )
{
	return Widget_GetPrivData( widget );
}

int LCUIWidget::addInvalidArea( LCUI_Rect area )
{
	return Widget_InvalidArea( widget, area );
}

int LCUIWidget::addInvalidArea( int x, int y, int w, int h )
{
	return Widget_InvalidArea( widget, Rect(x, y, w, h) );
}

void LCUIWidget::show( LCUI_BOOL need_show = TRUE )
{
	if(need_show) {
		Widget_Show( widget );
	} else {
		Widget_Hide( widget );
	}
}

void LCUIWidget::modal( LCUI_BOOL is_modal = TRUE )
{
	Widget_SetModal( widget, is_modal );
}

void LCUIWidget::dock( DOCK_TYPE dock_type )
{
	Widget_SetDock( widget, dock_type );
}

void LCUIWidget::move( LCUI_Pos new_pos )
{
	Widget_Move( widget, new_pos );
}

void LCUIWidget::move( int x, int y )
{
	Widget_Move( widget, Pos(x,y) );
}

void LCUIWidget::resize( LCUI_Size new_size )
{
	Widget_Resize( widget, new_size );
}

void LCUIWidget::resize( int w, int h )
{
	Widget_Resize( widget, Size(w,h) );
}

void LCUIWidget::update( LCUI_BOOL keep_new = FALSE )
{
	if( keep_new ) {
		Widget_Update( widget );
	} else {
		__Widget_Update( widget );
	}
}

void LCUIWidget::addChild( LCUI_Widget *child_widget )
{
	Widget_Container_Add( widget, child_widget );
}

void LCUIWidget::addChild( LCUIWidget &child_widget )
{
	Widget_Container_Add( widget, child_widget.getWidget() );
}

void LCUIWidget::getGraph( LCUI_Graph *graph_buff, LCUI_Rect rect )
{
	Widget_GetGraph( widget, graph_buff, rect );
}

LCUI_Graph* LCUIWidget::getSelfGraph( void )
{
	return Widget_GetSelfGraph( widget );
}

void LCUIWidget::syncInvalidArea( void )
{
	Widget_SyncInvalidArea( widget );
}

void LCUIWidget::setAlpha( unsigned char alpha )
{
	Widget_SetAlpha( widget, alpha );
}

void LCUIWidget::setPadding( int top, int bottom, int left, int right )
{
	Widget_SetPadding( widget, Padding(top, bottom, left, right) );
}

void LCUIWidget::setPadding( int top_bottom, int left_right )
{
	Widget_SetPadding( widget, Padding(top_bottom, top_bottom, left_right, left_right) );
}

void LCUIWidget::setPadding( int all )
{
	Widget_SetPadding( widget, Padding(all, all, all, all) );
}

void LCUIWidget::setBorder( unsigned int width_px, BORDER_STYLE style, LCUI_RGB color )
{
	Widget_SetBorder( widget, Border(width_px, style, color) );
}

void LCUIWidget::setBorderRadius( unsigned int radius )
{
	Widget_SetBorderRadius( widget, radius );
}

void LCUIWidget::setAlign( ALIGN_TYPE align, LCUI_Pos offset = Pos(0,0) )
{
	Widget_SetAlign( widget, align, offset );
}

void LCUIWidget::setBackgroundImage( LCUI_Graph *img )
{
	Widget_SetBackgroundImage( widget, img );
}

void LCUIWidget::setBackgroundLayout( LAYOUT_TYPE layout )
{
	Widget_SetBackgroundLayout( widget, layout );
}

void LCUIWidget::setBackgroundColor( LCUI_RGB color )
{
	Widget_SetBackgroundColor( widget, color );
}

void LCUIWidget::setBackgroundTransparent( LCUI_BOOL flag = TRUE )
{
	Widget_SetBackgroundTransparent( widget, flag );
}

void LCUIWidget::destroy( void )
{
	Widget_Destroy( widget );
}
#endif

#endif
<|endoftext|>