<commit_before>#ifndef ARABICA_XPATHIC_MATCH_REWRITE_HPP
#define ARABICA_XPATHIC_MATCH_REWRITE_HPP

namespace Arabica
{
namespace XPath
{

template<class string_type, class string_adaptor>
class ReplacementExpression : public XPathExpression_impl<string_type, string_adaptor>
{
public:
  ReplacementExpression(impl::NodeTest<string_type, string_adaptor>* test,
                        const std::vector<XPathExpression_impl<string_type, string_adaptor>*>& preds)
  {
    test_ = new impl::TestStepExpression<string_type, string_adaptor>(CHILD, test, preds);
  } // ReplacementExpression

  ~ReplacementExpression()
  {
    delete test_;
  } // ~ReplacementExpression

  virtual ValueType type() const { return BOOL; }

  virtual XPathValue<string_type, string_adaptor> evaluate(const DOM::Node<string_type, string_adaptor>& context,
                                                           const ExecutionContext<string_type, string_adaptor>& executionContext) const
  {
    DOM::Node<string_type, string_adaptor> parent = context.getParentNode();
    NodeSet<string_type, string_adaptor> nodes = test_->evaluateAsNodeSet(parent, executionContext);
    bool found = false;
    for(typename NodeSet<string_type, string_adaptor>::const_iterator n = nodes.begin(), ne = nodes.end();
        !found && (n != ne); ++n)
      found = (context == *n);
    return XPathValue<string_type, string_adaptor>(new BoolValue<string_type, string_adaptor>(found));
  } // evaluate

private:
  impl::TestStepExpression<string_type, string_adaptor>* test_;
}; // class ReplacementExpression

namespace impl
{
  template<class string_type, class string_adaptor>
  class PositionFnScanner : public Expression_scanner<string_type, string_adaptor>
  {
  public:
    PositionFnScanner() : found_(false) { }

    bool found() const { return found_; }

    virtual void scan(const XPathExpression_impl<string_type, string_adaptor>* const expr)
    {
      typedef FunctionHolder<string_type, string_adaptor> FH;
      const FH* const fn = dynamic_cast<const FH* const>(expr);
      if(fn == 0)
        return;

      if(!string_adaptor::empty(fn->namespace_uri()))
        return;

      found_ = found_ || ((fn->name() == FN_POSITION) || (fn->name() == FN_LAST));
    } // scan

  private:
    bool found_;

    static const string_type FN_POSITION;
    static const string_type FN_LAST;
  }; // class PositionFnScanner

  template<class string_type, class string_adaptor>
  const string_type PositionFnScanner<string_type, string_adaptor>::FN_POSITION = string_adaptor::construct_from_utf8("position");
  template<class string_type, class string_adaptor>
  const string_type PositionFnScanner<string_type, string_adaptor>::FN_LAST = string_adaptor::construct_from_utf8("last");

  template<class string_type, class string_adaptor>
  bool should_rewrite(XPathExpression_impl<string_type, string_adaptor>* expr)
  {
    if(expr->type() == NUMBER)
      return true;

    PositionFnScanner<string_type, string_adaptor> scanner;
    expr->scan(scanner);
    return scanner.found();
  } // should_rewrite
} // namespace impl

template<class string_type, class string_adaptor>
MatchExpr<string_type, string_adaptor>::MatchExpr(XPathExpression_impl<string_type, string_adaptor>* match, double priority) :
  match_(match), priority_(priority)
{
  typedef impl::RelativeLocationPath<string_type, string_adaptor> RelativeLocation;
  typedef impl::StepList<string_type, string_adaptor> StepList;
  typedef impl::TestStepExpression<string_type, string_adaptor> Step;
  typedef XPathExpression_impl<string_type, string_adaptor> Expression;
  typedef std::vector<Expression*> Predicates;
  // match is a RelativeLocationPath
  RelativeLocation* path = dynamic_cast<RelativeLocation*>(match);
  //   foreach step in the steplist
  StepList& steps = path->steps_;
  for(typename StepList::const_iterator s = steps.begin(), se = steps.end(); s != se; ++s)
  {
  //     foreach predicate in the predicatelist
    Step* step = dynamic_cast<Step*>(*s);
    if(step->has_predicates() == false)
      continue;

    Predicates& predicates = step->predicates_;
    Predicates::iterator positional = std::find_if(predicates.begin(), predicates.end(), impl::should_rewrite<string_type, string_adaptor>);
    while(positional != predicates.end())
    {
      Predicates folding(predicates.begin(), positional+1);
      Expression* replacement_expression = new ReplacementExpression<string_type, string_adaptor>(step->test_->clone(), folding);
      // replacement_expression now owns the leading predicates
      *positional = replacement_expression;
      // so remove the everyting upto the one we've just replaced
      predicates.erase(predicates.begin(), positional);
      positional = std::find_if(predicates.begin(), predicates.end(), impl::should_rewrite<string_type, string_adaptor>);
    } // while ...
  } // for(StepList::const_iterator ...
} // MatchExpr

} // namespace XPath

} // namespace Arabica

#endif
<commit_msg>added missing typename<commit_after>#ifndef ARABICA_XPATHIC_MATCH_REWRITE_HPP
#define ARABICA_XPATHIC_MATCH_REWRITE_HPP

namespace Arabica
{
namespace XPath
{

template<class string_type, class string_adaptor>
class ReplacementExpression : public XPathExpression_impl<string_type, string_adaptor>
{
public:
  ReplacementExpression(impl::NodeTest<string_type, string_adaptor>* test,
                        const std::vector<XPathExpression_impl<string_type, string_adaptor>*>& preds)
  {
    test_ = new impl::TestStepExpression<string_type, string_adaptor>(CHILD, test, preds);
  } // ReplacementExpression

  ~ReplacementExpression()
  {
    delete test_;
  } // ~ReplacementExpression

  virtual ValueType type() const { return BOOL; }

  virtual XPathValue<string_type, string_adaptor> evaluate(const DOM::Node<string_type, string_adaptor>& context,
                                                           const ExecutionContext<string_type, string_adaptor>& executionContext) const
  {
    DOM::Node<string_type, string_adaptor> parent = context.getParentNode();
    NodeSet<string_type, string_adaptor> nodes = test_->evaluateAsNodeSet(parent, executionContext);
    bool found = false;
    for(typename NodeSet<string_type, string_adaptor>::const_iterator n = nodes.begin(), ne = nodes.end();
        !found && (n != ne); ++n)
      found = (context == *n);
    return XPathValue<string_type, string_adaptor>(new BoolValue<string_type, string_adaptor>(found));
  } // evaluate

private:
  impl::TestStepExpression<string_type, string_adaptor>* test_;
}; // class ReplacementExpression

namespace impl
{
  template<class string_type, class string_adaptor>
  class PositionFnScanner : public Expression_scanner<string_type, string_adaptor>
  {
  public:
    PositionFnScanner() : found_(false) { }

    bool found() const { return found_; }

    virtual void scan(const XPathExpression_impl<string_type, string_adaptor>* const expr)
    {
      typedef FunctionHolder<string_type, string_adaptor> FH;
      const FH* const fn = dynamic_cast<const FH* const>(expr);
      if(fn == 0)
        return;

      if(!string_adaptor::empty(fn->namespace_uri()))
        return;

      found_ = found_ || ((fn->name() == FN_POSITION) || (fn->name() == FN_LAST));
    } // scan

  private:
    bool found_;

    static const string_type FN_POSITION;
    static const string_type FN_LAST;
  }; // class PositionFnScanner

  template<class string_type, class string_adaptor>
  const string_type PositionFnScanner<string_type, string_adaptor>::FN_POSITION = string_adaptor::construct_from_utf8("position");
  template<class string_type, class string_adaptor>
  const string_type PositionFnScanner<string_type, string_adaptor>::FN_LAST = string_adaptor::construct_from_utf8("last");

  template<class string_type, class string_adaptor>
  bool should_rewrite(XPathExpression_impl<string_type, string_adaptor>* expr)
  {
    if(expr->type() == NUMBER)
      return true;

    PositionFnScanner<string_type, string_adaptor> scanner;
    expr->scan(scanner);
    return scanner.found();
  } // should_rewrite
} // namespace impl

template<class string_type, class string_adaptor>
MatchExpr<string_type, string_adaptor>::MatchExpr(XPathExpression_impl<string_type, string_adaptor>* match, double priority) :
  match_(match), priority_(priority)
{
  typedef impl::RelativeLocationPath<string_type, string_adaptor> RelativeLocation;
  typedef impl::StepList<string_type, string_adaptor> StepList;
  typedef impl::TestStepExpression<string_type, string_adaptor> Step;
  typedef XPathExpression_impl<string_type, string_adaptor> Expression;
  typedef std::vector<Expression*> Predicates;
  // match is a RelativeLocationPath
  RelativeLocation* path = dynamic_cast<RelativeLocation*>(match);
  //   foreach step in the steplist
  StepList& steps = path->steps_;
  for(typename StepList::const_iterator s = steps.begin(), se = steps.end(); s != se; ++s)
  {
  //     foreach predicate in the predicatelist
    Step* step = dynamic_cast<Step*>(*s);
    if(step->has_predicates() == false)
      continue;

    Predicates& predicates = step->predicates_;
    typename Predicates::iterator positional = std::find_if(predicates.begin(), predicates.end(), impl::should_rewrite<string_type, string_adaptor>);
    while(positional != predicates.end())
    {
      Predicates folding(predicates.begin(), positional+1);
      Expression* replacement_expression = new ReplacementExpression<string_type, string_adaptor>(step->test_->clone(), folding);
      // replacement_expression now owns the leading predicates
      *positional = replacement_expression;
      // so remove the everyting upto the one we've just replaced
      predicates.erase(predicates.begin(), positional);
      positional = std::find_if(predicates.begin(), predicates.end(), impl::should_rewrite<string_type, string_adaptor>);
    } // while ...
  } // for(StepList::const_iterator ...
} // MatchExpr

} // namespace XPath

} // namespace Arabica

#endif
<|endoftext|>


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

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

#include "checkpoints.h"

#include "main.h"
#include "uint256.h"

namespace Checkpoints
{
    typedef std::map<int, uint256> MapCheckpoints;

    // How many times we expect transactions after the last checkpoint to
    // be slower. This number is a compromise, as it can't be accurate for
    // every system. When reindexing from a fast disk with a slow CPU, it
    // can be up to 20, while when downloading from a slow network with a
    // fast multicore CPU, it won't be much higher than 1.
    static const double fSigcheckVerificationFactor = 5.0;

    struct CCheckpointData {
        const MapCheckpoints *mapCheckpoints;
        int64 nTimeLastCheckpoint;
        int64 nTransactionsLastCheckpoint;
        double fTransactionsPerDay;
    };

    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions
    static MapCheckpoints mapCheckpoints =
        boost::assign::map_list_of
        (     0, uint256("0x56ab86a29b0948a69ef408aaa36b1c571f9f0d56577e6ff2813ed1115fbcc932"))
        ;
    static const CCheckpointData data = {
        &mapCheckpoints,
        1393953490, // * UNIX timestamp of last checkpoint block
        0,    // * total number of transactions between genesis and last checkpoint
                    //   (the tx=... number in the SetBestChain debug.log lines)
        8000.0     // * estimated number of transactions per day after checkpoint
    };

    static MapCheckpoints mapCheckpointsTestnet =
        boost::assign::map_list_of
        ( 35000, uint256("2af959ab4f12111ce947479bfcef16702485f04afd95210aa90fde7d1e4a64ad"))
        ;
    static const CCheckpointData dataTestnet = {
        &mapCheckpointsTestnet,
        1369685559,
        37581,
        300
    };

    const CCheckpointData &Checkpoints() {
        if (fTestNet)
            return dataTestnet;
        else
            return data;
    }

    bool CheckBlock(int nHeight, const uint256& hash)
    {
        if (fTestNet) return true; // Testnet has no checkpoints
        if (!GetBoolArg("-checkpoints", true))
            return true;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) return true;
        return hash == i->second;
    }

    // Guess how far we are in the verification process at the given block index
    double GuessVerificationProgress(CBlockIndex *pindex) {
        if (pindex==NULL)
            return 0.0;

        int64 nNow = time(NULL);

        double fWorkBefore = 0.0; // Amount of work done before pindex
        double fWorkAfter = 0.0;  // Amount of work left after pindex (estimated)
        // Work is defined as: 1.0 per transaction before the last checkoint, and
        // fSigcheckVerificationFactor per transaction after.

        const CCheckpointData &data = Checkpoints();

        if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
            double nCheapBefore = pindex->nChainTx;
            double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
            double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore;
            fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
        } else {
            double nCheapBefore = data.nTransactionsLastCheckpoint;
            double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
            double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
            fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
        }

        return fWorkBefore / (fWorkBefore + fWorkAfter);
    }

    int GetTotalBlocksEstimate()
    {
        if (fTestNet) return 0; // Testnet has no checkpoints
        if (!GetBoolArg("-checkpoints", true))
            return 0;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        if (fTestNet) return NULL; // Testnet has no checkpoints
        if (!GetBoolArg("-checkpoints", true))
            return NULL;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
        {
            const uint256& hash = i.second;
            std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                return t->second;
        }
        return NULL;
    }
}
<commit_msg>updated checkpoints with timestamps<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

#include "checkpoints.h"

#include "main.h"
#include "uint256.h"

namespace Checkpoints
{
    typedef std::map<int, uint256> MapCheckpoints;

    // How many times we expect transactions after the last checkpoint to
    // be slower. This number is a compromise, as it can't be accurate for
    // every system. When reindexing from a fast disk with a slow CPU, it
    // can be up to 20, while when downloading from a slow network with a
    // fast multicore CPU, it won't be much higher than 1.
    static const double fSigcheckVerificationFactor = 5.0;

    struct CCheckpointData {
        const MapCheckpoints *mapCheckpoints;
        int64 nTimeLastCheckpoint;
        int64 nTransactionsLastCheckpoint;
        double fTransactionsPerDay;
    };

    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions
    static MapCheckpoints mapCheckpoints =
        boost::assign::map_list_of
        (     0, uint256("0xbdf025df56b8d992f3c3f0e9f626ad88aacfa439213abc6c21417118c120cc06"))
        ;
    static const CCheckpointData data = {
        &mapCheckpoints,
        1393590000, // * UNIX timestamp of last checkpoint block
        0,    // * total number of transactions between genesis and last checkpoint
                    //   (the tx=... number in the SetBestChain debug.log lines)
        8000.0     // * estimated number of transactions per day after checkpoint
    };

    static MapCheckpoints mapCheckpointsTestnet =
        boost::assign::map_list_of
        (     0, uint256("0xbdf025df56b8d992f3c3f0e9f626ad88aacfa439213abc6c21417118c120cc06"))
        ;
    static const CCheckpointData dataTestnet = {
        &mapCheckpointsTestnet,
        1393590000, // * UNIX timestamp of last checkpoint block
        0,    // * total number of transactions between genesis and last checkpoint
                    //   (the tx=... number in the SetBestChain debug.log lines)
        8000.0     // * estimated number of transactions per day after checkpoint
    };

    const CCheckpointData &Checkpoints() {
        if (fTestNet)
            return dataTestnet;
        else
            return data;
    }

    bool CheckBlock(int nHeight, const uint256& hash)
    {
        if (fTestNet) return true; // Testnet has no checkpoints
        if (!GetBoolArg("-checkpoints", true))
            return true;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) return true;
        return hash == i->second;
    }

    // Guess how far we are in the verification process at the given block index
    double GuessVerificationProgress(CBlockIndex *pindex) {
        if (pindex==NULL)
            return 0.0;

        int64 nNow = time(NULL);

        double fWorkBefore = 0.0; // Amount of work done before pindex
        double fWorkAfter = 0.0;  // Amount of work left after pindex (estimated)
        // Work is defined as: 1.0 per transaction before the last checkoint, and
        // fSigcheckVerificationFactor per transaction after.

        const CCheckpointData &data = Checkpoints();

        if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
            double nCheapBefore = pindex->nChainTx;
            double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
            double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore;
            fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
        } else {
            double nCheapBefore = data.nTransactionsLastCheckpoint;
            double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
            double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
            fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
        }

        return fWorkBefore / (fWorkBefore + fWorkAfter);
    }

    int GetTotalBlocksEstimate()
    {
        if (fTestNet) return 0; // Testnet has no checkpoints
        if (!GetBoolArg("-checkpoints", true))
            return 0;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        if (fTestNet) return NULL; // Testnet has no checkpoints
        if (!GetBoolArg("-checkpoints", true))
            return NULL;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
        {
            const uint256& hash = i.second;
            std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                return t->second;
        }
        return NULL;
    }
}<|endoftext|>


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

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

#include "checkpoints.h"

#include "main.h"
#include "uint256.h"

namespace Checkpoints
{
    typedef std::map<int, uint256> MapCheckpoints;

    // How many times we expect transactions after the last checkpoint to
    // be slower. This number is a compromise, as it can't be accurate for
    // every system. When reindexing from a fast disk with a slow CPU, it
    // can be up to 20, while when downloading from a slow network with a
    // fast multicore CPU, it won't be much higher than 1.
    static const double fSigcheckVerificationFactor = 5.0;

    struct CCheckpointData {
        const MapCheckpoints *mapCheckpoints;
        int64 nTimeLastCheckpoint;
        int64 nTransactionsLastCheckpoint;
        double fTransactionsPerDay;
    };

    bool fEnabled = true;

    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions
    static MapCheckpoints mapCheckpoints =
        boost::assign::map_list_of
        ( 0,     uint256("0x00000bb87d9514374986aeea9a275fab8465d575b2383654ebb6944460f00037"))
        ( 20160, uint256("0x00000000000176d0af32856ba528354707338bc3890192e5988712331e10bbba"))
        //( 0, uint256("0x"))

        ;
    static const CCheckpointData data = {
        &mapCheckpoints,
        1388874174, // * UNIX timestamp of last checkpoint block
        0, //842057,     // * total number of transactions between genesis and last checkpoint
                    //   (the tx=... number in the SetBestChain debug.log lines)
        2880        // * estimated number of transactions per day after checkpoint
    };

    static MapCheckpoints mapCheckpointsTestnet =
        boost::assign::map_list_of
        ( 0, uint256("0x00000d6feb89798a1bfb43642647d3549b69efeece1da75d7edc8730ab5e933d"))
        ;
    static const CCheckpointData dataTestnet = {
        &mapCheckpointsTestnet,
        1391126157,
        0,
        2880
    };

    const CCheckpointData &Checkpoints() {
        if (TestNet())
            return dataTestnet;
        else
            return data;
    }

    bool CheckBlock(int nHeight, const uint256& hash)
    {
        if (!fEnabled)
            return true;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) return true;

        //fake123
        return hash == i->second;
        //return true;
    }

    // Guess how far we are in the verification process at the given block index
    double GuessVerificationProgress(CBlockIndex *pindex) {
        if (pindex==NULL)
            return 0.0;

        int64 nNow = time(NULL);

        double fWorkBefore = 0.0; // Amount of work done before pindex
        double fWorkAfter = 0.0;  // Amount of work left after pindex (estimated)
        // Work is defined as: 1.0 per transaction before the last checkoint, and
        // fSigcheckVerificationFactor per transaction after.

        const CCheckpointData &data = Checkpoints();

        if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
            double nCheapBefore = pindex->nChainTx;
            double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
            double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore;
            fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
        } else {
            double nCheapBefore = data.nTransactionsLastCheckpoint;
            double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
            double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
            fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
        }

        return fWorkBefore / (fWorkBefore + fWorkAfter);
    }

    int GetTotalBlocksEstimate()
    {
        if (!fEnabled)
            return 0;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
		//fake123
        return checkpoints.rbegin()->first;
        //return 0;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        if (!fEnabled)
            return NULL;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
        {
            const uint256& hash = i.second;
            std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                //fake123
                return t->second;
                //return NULL;
        }
        return NULL;
    }
}
<commit_msg>updated checkpoint<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

#include "checkpoints.h"

#include "main.h"
#include "uint256.h"

namespace Checkpoints
{
    typedef std::map<int, uint256> MapCheckpoints;

    // How many times we expect transactions after the last checkpoint to
    // be slower. This number is a compromise, as it can't be accurate for
    // every system. When reindexing from a fast disk with a slow CPU, it
    // can be up to 20, while when downloading from a slow network with a
    // fast multicore CPU, it won't be much higher than 1.
    static const double fSigcheckVerificationFactor = 5.0;

    struct CCheckpointData {
        const MapCheckpoints *mapCheckpoints;
        int64 nTimeLastCheckpoint;
        int64 nTransactionsLastCheckpoint;
        double fTransactionsPerDay;
    };

    bool fEnabled = true;

    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions
    static MapCheckpoints mapCheckpoints =
        boost::assign::map_list_of
        ( 0,     uint256("0x00000bb87d9514374986aeea9a275fab8465d575b2383654ebb6944460f00037"))
        ( 20160, uint256("0x00000000000176d0af32856ba528354707338bc3890192e5988712331e10bbba"))
        ( 40320, uint256("0x00000000000149f1222dffe7b8698389326d9473cbc1b4c80e271bf620ff7551"))

        //( 0, uint256("0x"))

        ;
    static const CCheckpointData data = {
        &mapCheckpoints,
        1391627217, // * UNIX timestamp of last checkpoint block
        0, //842057,     // * total number of transactions between genesis and last checkpoint
                    //   (the tx=... number in the SetBestChain debug.log lines)
        2880        // * estimated number of transactions per day after checkpoint
    };

    static MapCheckpoints mapCheckpointsTestnet =
        boost::assign::map_list_of
        ( 0, uint256("0x00000d6feb89798a1bfb43642647d3549b69efeece1da75d7edc8730ab5e933d"))
        ;
    static const CCheckpointData dataTestnet = {
        &mapCheckpointsTestnet,
        1391126157,
        0,
        2880
    };

    const CCheckpointData &Checkpoints() {
        if (TestNet())
            return dataTestnet;
        else
            return data;
    }

    bool CheckBlock(int nHeight, const uint256& hash)
    {
        if (!fEnabled)
            return true;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) return true;

        //fake123
        return hash == i->second;
        //return true;
    }

    // Guess how far we are in the verification process at the given block index
    double GuessVerificationProgress(CBlockIndex *pindex) {
        if (pindex==NULL)
            return 0.0;

        int64 nNow = time(NULL);

        double fWorkBefore = 0.0; // Amount of work done before pindex
        double fWorkAfter = 0.0;  // Amount of work left after pindex (estimated)
        // Work is defined as: 1.0 per transaction before the last checkoint, and
        // fSigcheckVerificationFactor per transaction after.

        const CCheckpointData &data = Checkpoints();

        if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
            double nCheapBefore = pindex->nChainTx;
            double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
            double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore;
            fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
        } else {
            double nCheapBefore = data.nTransactionsLastCheckpoint;
            double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
            double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
            fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
        }

        return fWorkBefore / (fWorkBefore + fWorkAfter);
    }

    int GetTotalBlocksEstimate()
    {
        if (!fEnabled)
            return 0;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
		//fake123
        return checkpoints.rbegin()->first;
        //return 0;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        if (!fEnabled)
            return NULL;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
        {
            const uint256& hash = i.second;
            std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                //fake123
                return t->second;
                //return NULL;
        }
        return NULL;
    }
}
<|endoftext|>


<commit_before>#pragma once

#include "Shape.hpp"

#include <memory>
#include <set>
#include <vector>

namespace Geometry2d {

/// This class maintains a collection of Shape objects.
class ShapeSet {
public:
    ShapeSet() {}

    /// Initializes the set by iterating from @first to @last, which are
    /// iterators into a collection of std::shared_ptr<Shape>.
    template <class InputIt>
    ShapeSet(InputIt first, InputIt last) {
        while (first != last) {
            add(*first++);
        }
    }

    std::vector<std::shared_ptr<Shape>> shapes() { return _shapes; }
    const std::vector<std::shared_ptr<Shape>> shapes() const { return _shapes; }

    void add(std::shared_ptr<Shape> shape) {
        if (!shape)
            throw std::runtime_error("Attempt to add null shape to ShapeSet");
        _shapes.push_back(shape);
    }

    void add(const ShapeSet& other) {
        for (auto shape : other.shapes()) {
            add(shape);
        }
    }

    /// Remove all shapes
    void clear() { _shapes.clear(); }

    /**
     * Get a set of which shapes "hit" the given object.
     *
     * @param obj The object to collision test
     * @return A set of all shapes that collide with the given object
     */
    template <typename T>
    std::set<std::shared_ptr<Shape>> hitSet(const T& obj) const {
        std::set<std::shared_ptr<Shape>> hits;
        for (const auto& shape : _shapes) {
            if (shape->hit(obj)) {
                hits.insert(shape);
            }
        }
        return hits;
    }

    /**
     * Check if any of the shapes in this set "hit" the given object.
     *
     * @param obj The object to collision test
     * @return True if one of the contained shapes hits the object.
     */
    template <typename T>
    bool hit(const T& obj) const {
        return !hitSet<T>(obj).empty();
    }

private:
    std::vector<std::shared_ptr<Shape>> _shapes;
};

}  // namespace Geometry2d
<commit_msg>added operator<<() to ShapeSet<commit_after>#pragma once

#include "Shape.hpp"

#include <memory>
#include <set>
#include <sstream>
#include <vector>

namespace Geometry2d {

/// This class maintains a collection of Shape objects.
class ShapeSet {
public:
    ShapeSet() {}

    /// Initializes the set by iterating from @first to @last, which are
    /// iterators into a collection of std::shared_ptr<Shape>.
    template <class InputIt>
    ShapeSet(InputIt first, InputIt last) {
        while (first != last) {
            add(*first++);
        }
    }

    std::vector<std::shared_ptr<Shape>> shapes() { return _shapes; }
    const std::vector<std::shared_ptr<Shape>> shapes() const { return _shapes; }

    void add(std::shared_ptr<Shape> shape) {
        if (!shape)
            throw std::runtime_error("Attempt to add null shape to ShapeSet");
        _shapes.push_back(shape);
    }

    void add(const ShapeSet& other) {
        for (auto shape : other.shapes()) {
            add(shape);
        }
    }

    /// Remove all shapes
    void clear() { _shapes.clear(); }

    /**
     * Get a set of which shapes "hit" the given object.
     *
     * @param obj The object to collision test
     * @return A set of all shapes that collide with the given object
     */
    template <typename T>
    std::set<std::shared_ptr<Shape>> hitSet(const T& obj) const {
        std::set<std::shared_ptr<Shape>> hits;
        for (const auto& shape : _shapes) {
            if (shape->hit(obj)) {
                hits.insert(shape);
            }
        }
        return hits;
    }

    /**
     * Check if any of the shapes in this set "hit" the given object.
     *
     * @param obj The object to collision test
     * @return True if one of the contained shapes hits the object.
     */
    template <typename T>
    bool hit(const T& obj) const {
        return !hitSet<T>(obj).empty();
    }

    friend std::ostream& operator<<(std::ostream& out, const ShapeSet& shapeSet) {
        out << "ShapeSet: {";
        for (const auto& shape : shapeSet.shapes()) {
            out << shape->toString() << ", ";
        }
        out << "}";
        return out;
    }

private:
    std::vector<std::shared_ptr<Shape>> _shapes;
};

}  // namespace Geometry2d
<|endoftext|>


<commit_before>/**
 * \file
 * \brief Directory class header
 *
 * \author Copyright (C) 2018-2019 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#ifndef INCLUDE_DISTORTOS_FILESYSTEM_DIRECTORY_HPP_
#define INCLUDE_DISTORTOS_FILESYSTEM_DIRECTORY_HPP_

#include <dirent.h>

#include <utility>

namespace distortos
{

/**
 * Directory class is an interface for a directory.
 *
 * \ingroup fileSystem
 */

class Directory
{
public:

	/**
	 * \brief Directory's destructor
	 *
	 * \pre %Directory is closed.
	 */

	virtual ~Directory() = default;

	/**
	 * \brief Closes directory.
	 *
	 * Similar to [closedir()](http://pubs.opengroup.org/onlinepubs/9699919799/functions/closedir.html)
	 *
	 * \note Even if error code is returned, the directory must not be used.
	 *
	 * \pre %Directory is opened.
	 *
	 * \post %Directory is closed.
	 *
	 * \return 0 on success, error code otherwise
	 */

	virtual int close() = 0;

	/**
	 * \brief Returns current position in the directory.
	 *
	 * Similar to [telldir()](http://pubs.opengroup.org/onlinepubs/9699919799/functions/telldir.html)
	 *
	 * \pre %Directory is opened.
	 *
	 * \return pair with return code (0 on success, error code otherwise) and current position in the directory
	 */

	virtual std::pair<int, off_t> getPosition() = 0;

	/**
	 * \brief Locks the directory for exclusive use by current thread.
	 *
	 * When the object is locked, any call to any member function from other thread will be blocked until the object is
	 * unlocked. Locking is optional, but may be useful when more than one operation must be done atomically.
	 *
	 * \note Locks are recursive.
	 *
	 * \warning This function must not be called from interrupt context!
	 *
	 * \pre The number of recursive locks of directory is less than 65535.
	 *
	 * \post %Directory is locked.
	 */

	virtual void lock() = 0;

	/**
	 * \brief Reads next entry from directory.
	 *
	 * Similar to [readdir_r()](http://pubs.opengroup.org/onlinepubs/9699919799/functions/readdir.html)
	 *
	 * \pre %Directory is opened.
	 *
	 * \param [out] entry is a reference to `dirent` struct into which next entry from directory will be written
	 *
	 * \return 0 on success, error code otherwise:
	 * - ENOENT - current position in the directory is invalid (i.e. end of the directory reached);
	 */

	virtual int read(dirent& entry) = 0;

	/**
	 * \brief Resets current position in the directory.
	 *
	 * Similar to [rewinddir()](http://pubs.opengroup.org/onlinepubs/9699919799/functions/rewinddir.html)
	 *
	 * \pre %Directory is opened.
	 *
	 * \return 0 on success, error code otherwise
	 */

	virtual int rewind() = 0;

	/**
	 * \brief Moves position in the directory.
	 *
	 * Similar to [seekdir()](http://pubs.opengroup.org/onlinepubs/9699919799/functions/seekdir.html)
	 *
	 * \pre %Directory is opened.
	 *
	 * \param [in] position is the value of position, must be a value previously returned by getPosition()!
	 *
	 * \return 0 on success, error code otherwise
	 */

	virtual int seek(off_t position) = 0;

	/**
	 * \brief Unlocks the directory which was previously locked by current thread.
	 *
	 * \note Locks are recursive.
	 *
	 * \warning This function must not be called from interrupt context!
	 *
	 * \pre This function is called by the thread that locked the directory.
	 */

	virtual void unlock() = 0;

	Directory() = default;
	Directory(const Directory&) = delete;
	Directory& operator=(const Directory&) = delete;
};

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_FILESYSTEM_DIRECTORY_HPP_
<commit_msg>Include <cstdio> in Directory.hpp<commit_after>/**
 * \file
 * \brief Directory class header
 *
 * \author Copyright (C) 2018-2019 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#ifndef INCLUDE_DISTORTOS_FILESYSTEM_DIRECTORY_HPP_
#define INCLUDE_DISTORTOS_FILESYSTEM_DIRECTORY_HPP_

#include <dirent.h>

#include <utility>

#include <cstdio>

namespace distortos
{

/**
 * Directory class is an interface for a directory.
 *
 * \ingroup fileSystem
 */

class Directory
{
public:

	/**
	 * \brief Directory's destructor
	 *
	 * \pre %Directory is closed.
	 */

	virtual ~Directory() = default;

	/**
	 * \brief Closes directory.
	 *
	 * Similar to [closedir()](http://pubs.opengroup.org/onlinepubs/9699919799/functions/closedir.html)
	 *
	 * \note Even if error code is returned, the directory must not be used.
	 *
	 * \pre %Directory is opened.
	 *
	 * \post %Directory is closed.
	 *
	 * \return 0 on success, error code otherwise
	 */

	virtual int close() = 0;

	/**
	 * \brief Returns current position in the directory.
	 *
	 * Similar to [telldir()](http://pubs.opengroup.org/onlinepubs/9699919799/functions/telldir.html)
	 *
	 * \pre %Directory is opened.
	 *
	 * \return pair with return code (0 on success, error code otherwise) and current position in the directory
	 */

	virtual std::pair<int, off_t> getPosition() = 0;

	/**
	 * \brief Locks the directory for exclusive use by current thread.
	 *
	 * When the object is locked, any call to any member function from other thread will be blocked until the object is
	 * unlocked. Locking is optional, but may be useful when more than one operation must be done atomically.
	 *
	 * \note Locks are recursive.
	 *
	 * \warning This function must not be called from interrupt context!
	 *
	 * \pre The number of recursive locks of directory is less than 65535.
	 *
	 * \post %Directory is locked.
	 */

	virtual void lock() = 0;

	/**
	 * \brief Reads next entry from directory.
	 *
	 * Similar to [readdir_r()](http://pubs.opengroup.org/onlinepubs/9699919799/functions/readdir.html)
	 *
	 * \pre %Directory is opened.
	 *
	 * \param [out] entry is a reference to `dirent` struct into which next entry from directory will be written
	 *
	 * \return 0 on success, error code otherwise:
	 * - ENOENT - current position in the directory is invalid (i.e. end of the directory reached);
	 */

	virtual int read(dirent& entry) = 0;

	/**
	 * \brief Resets current position in the directory.
	 *
	 * Similar to [rewinddir()](http://pubs.opengroup.org/onlinepubs/9699919799/functions/rewinddir.html)
	 *
	 * \pre %Directory is opened.
	 *
	 * \return 0 on success, error code otherwise
	 */

	virtual int rewind() = 0;

	/**
	 * \brief Moves position in the directory.
	 *
	 * Similar to [seekdir()](http://pubs.opengroup.org/onlinepubs/9699919799/functions/seekdir.html)
	 *
	 * \pre %Directory is opened.
	 *
	 * \param [in] position is the value of position, must be a value previously returned by getPosition()!
	 *
	 * \return 0 on success, error code otherwise
	 */

	virtual int seek(off_t position) = 0;

	/**
	 * \brief Unlocks the directory which was previously locked by current thread.
	 *
	 * \note Locks are recursive.
	 *
	 * \warning This function must not be called from interrupt context!
	 *
	 * \pre This function is called by the thread that locked the directory.
	 */

	virtual void unlock() = 0;

	Directory() = default;
	Directory(const Directory&) = delete;
	Directory& operator=(const Directory&) = delete;
};

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_FILESYSTEM_DIRECTORY_HPP_
<|endoftext|>


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

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

#include "checkpoints.h"

#include "txdb.h"
#include "main.h"
#include "uint256.h"

static const int nCheckpointSpan = 5000;

namespace Checkpoints
{
    typedef std::map<int, uint256> MapCheckpoints;

    //
    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions
    //
    static MapCheckpoints mapCheckpoints =
        boost::assign::map_list_of
		(     0, Params().HashGenesisBlock() )
    ;

    // TestNet has no checkpoints
    static MapCheckpoints mapCheckpointsTestnet;

    bool CheckHardened(int nHeight, const uint256& hash)
    {
        MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints);

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) return true;
        return hash == i->second;
    }

    int GetTotalBlocksEstimate()
    {
        MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints);

        if (checkpoints.empty())
            return 0;
        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints);

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
        {
            const uint256& hash = i.second;
            std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                return t->second;
        }
        return NULL;
    }

    // Automatically select a suitable sync-checkpoint
    const CBlockIndex* AutoSelectSyncCheckpoint()
    {
        const CBlockIndex *pindex = pindexBest;
        // Search backward for a block within max span and maturity window
        while (pindex->pprev && pindex->nHeight + nCheckpointSpan > pindexBest->nHeight)
            pindex = pindex->pprev;
        return pindex;
    }

    // Check against synchronized checkpoint
    bool CheckSync(int nHeight)
    {
        const CBlockIndex* pindexSync = AutoSelectSyncCheckpoint();
        if (nHeight <= pindexSync->nHeight){
            return false;
        }
        return true;
    }
}
<commit_msg>Add checkpoints<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

#include "checkpoints.h"

#include "txdb.h"
#include "main.h"
#include "uint256.h"

static const int nCheckpointSpan = 5000;

namespace Checkpoints
{
    typedef std::map<int, uint256> MapCheckpoints;

    //
    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions
    //
    static MapCheckpoints mapCheckpoints =
        boost::assign::map_list_of
		(     0, Params().HashGenesisBlock() )
		(  1, uint256("0x96f8969adf071fb172db7a6e6a4e71cd9a01d4b730e11a405b344409a013f5f2"))
		(  5, uint256("0xd91f414ab9bd5ceb57574b1df8c1512cd53667ac785baa65ccb4844a0d7bd945"))
    ;

    // TestNet has no checkpoints
    static MapCheckpoints mapCheckpointsTestnet;

    bool CheckHardened(int nHeight, const uint256& hash)
    {
        MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints);

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) return true;
        return hash == i->second;
    }

    int GetTotalBlocksEstimate()
    {
        MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints);

        if (checkpoints.empty())
            return 0;
        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints);

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
        {
            const uint256& hash = i.second;
            std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                return t->second;
        }
        return NULL;
    }

    // Automatically select a suitable sync-checkpoint
    const CBlockIndex* AutoSelectSyncCheckpoint()
    {
        const CBlockIndex *pindex = pindexBest;
        // Search backward for a block within max span and maturity window
        while (pindex->pprev && pindex->nHeight + nCheckpointSpan > pindexBest->nHeight)
            pindex = pindex->pprev;
        return pindex;
    }

    // Check against synchronized checkpoint
    bool CheckSync(int nHeight)
    {
        const CBlockIndex* pindexSync = AutoSelectSyncCheckpoint();
        if (nHeight <= pindexSync->nHeight){
            return false;
        }
        return true;
    }
}
<|endoftext|>


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

#ifndef FMICPP_FMUINSTANCE_HPP
#define FMICPP_FMUINSTANCE_HPP

#include <vector>
#include <string>
#include "../xml/ModelDescription.hpp"
#include "../fmi2Functions.h"

using std::vector;

namespace fmicpp::fmi2::import {

    class FmuInstance {

    protected:

        double simulationTime_ = 0.0;

        bool instantiated_ = false;
        bool terminated_ = false;

    public:

        virtual const double getSimulationTime() const {
            return simulationTime_;
        }

        virtual const bool isInstantiated() const {
            return instantiated_;
        }

        virtual const bool isTerminated() const {
            return terminated_;
        }

        virtual const fmi2ValueReference getValueReference(const std::string &name) const {
            return getModelDescription().getVariableByName(name).valueReference;
        }

        virtual const xml::ModelDescription& getModelDescription() const = 0;

        virtual void init(const double start = 0, const double stop = 0) = 0;

        virtual fmi2Status reset() = 0;

        virtual fmi2Status terminate() = 0;

        virtual bool canGetAndSetFMUstate() const = 0;

        virtual fmi2Status getFMUstate(fmi2FMUstate &state) = 0;

        virtual fmi2Status setFMUstate(const fmi2FMUstate state) = 0;

        virtual fmi2Status freeFMUstate(fmi2FMUstate &state) = 0;

        virtual bool canSerializeFmuState() const = 0;

        virtual fmi2Status serializeFMUstate(const fmi2FMUstate &state, vector<fmi2Byte> &serializedState) = 0;

        virtual fmi2Status deSerializeFMUstate(fmi2FMUstate &state, const vector<fmi2Byte> &serializedState) = 0;

        virtual bool providesDirectionalDerivative() const = 0;

        virtual fmi2Status getDirectionalDerivative(
                const vector<fmi2ValueReference> &vUnkownRef,
                const vector<fmi2ValueReference > &vKnownRef,
                const vector<fmi2Real> &dvKnownRef,
                vector<fmi2Real> &dvUnknownRef) const = 0;

        virtual fmi2Status readInteger(const string &name, fmi2Integer &ref) const {
            const auto vr = getModelDescription().modelVariables.getByName(name).valueReference;
            return readInteger(vr, ref);
        }
        virtual fmi2Status readInteger(const fmi2ValueReference vr, fmi2Integer &ref) const = 0;
        virtual fmi2Status readInteger(const vector<fmi2ValueReference> &vr, vector<fmi2Integer> &ref) const = 0;

        virtual fmi2Status readReal(const string &name, fmi2Real &ref) const {
            const auto vr = getModelDescription().modelVariables.getByName(name).valueReference;
            return readReal(vr, ref);
        }
        virtual fmi2Status readReal(const fmi2ValueReference vr, fmi2Real &ref) const = 0;
        virtual fmi2Status readReal(const vector<fmi2ValueReference> &vr, vector<fmi2Real> &ref) const = 0;

        virtual fmi2Status readString(const string &name, fmi2String &ref) const {
            const auto vr = getModelDescription().modelVariables.getByName(name).valueReference;
            return readString(vr, ref);
        }
        virtual fmi2Status readString(const fmi2ValueReference vr, fmi2String &ref) const = 0;
        virtual fmi2Status readString(const vector<fmi2ValueReference> &vr, vector<fmi2String> &ref) const = 0;

        virtual fmi2Status readBoolean(const string &name, fmi2Boolean &ref) const {
            const auto vr = getModelDescription().modelVariables.getByName(name).valueReference;
            return readBoolean(vr, ref);
        }
        virtual fmi2Status readBoolean(const fmi2ValueReference vr, fmi2Boolean &ref) const = 0;
        virtual fmi2Status readBoolean(const vector<fmi2ValueReference> &vr, vector<fmi2Boolean> &ref) const = 0;

        virtual ~FmuInstance() {};

    };

}

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

#ifndef FMICPP_FMUINSTANCE_HPP
#define FMICPP_FMUINSTANCE_HPP

#include <vector>
#include <string>
#include "../xml/ModelDescription.hpp"
#include "../fmi2Functions.h"

using std::vector;

namespace fmicpp::fmi2::import {

    class FmuInstance {

    protected:

        double simulationTime_ = 0.0;

        bool instantiated_ = false;
        bool terminated_ = false;

    public:

        virtual const double getSimulationTime() const {
            return simulationTime_;
        }

        virtual const bool isInstantiated() const {
            return instantiated_;
        }

        virtual const bool isTerminated() const {
            return terminated_;
        }

        virtual const fmi2ValueReference getValueReference(const std::string &name) const {
            return getModelDescription().getVariableByName(name).valueReference;
        }

        virtual const xml::ModelDescription& getModelDescription() const = 0;

        virtual void init(const double start = 0, const double stop = 0) = 0;

        virtual fmi2Status reset() = 0;

        virtual fmi2Status terminate() = 0;

        virtual bool canGetAndSetFMUstate() const = 0;

        virtual fmi2Status getFMUstate(fmi2FMUstate &state) = 0;

        virtual fmi2Status setFMUstate(const fmi2FMUstate state) = 0;

        virtual fmi2Status freeFMUstate(fmi2FMUstate &state) = 0;

        virtual bool canSerializeFmuState() const = 0;

        virtual fmi2Status serializeFMUstate(const fmi2FMUstate &state, vector<fmi2Byte> &serializedState) = 0;

        virtual fmi2Status deSerializeFMUstate(fmi2FMUstate &state, const vector<fmi2Byte> &serializedState) = 0;

        virtual bool providesDirectionalDerivative() const = 0;

        virtual fmi2Status getDirectionalDerivative(
                const vector<fmi2ValueReference> &vUnkownRef,
                const vector<fmi2ValueReference > &vKnownRef,
                const vector<fmi2Real> &dvKnownRef,
                vector<fmi2Real> &dvUnknownRef) const = 0;

        virtual fmi2Status readInteger(const string &name, fmi2Integer &ref) const {
            const auto vr = getModelDescription().getVariableByName(name).valueReference;;
            return readInteger(vr, ref);
        }
        virtual fmi2Status readInteger(const fmi2ValueReference vr, fmi2Integer &ref) const = 0;
        virtual fmi2Status readInteger(const vector<fmi2ValueReference> &vr, vector<fmi2Integer> &ref) const = 0;

        virtual fmi2Status readReal(const string &name, fmi2Real &ref) const {
            const auto vr = getModelDescription().getVariableByName(name).valueReference;;
            return readReal(vr, ref);
        }
        virtual fmi2Status readReal(const fmi2ValueReference vr, fmi2Real &ref) const = 0;
        virtual fmi2Status readReal(const vector<fmi2ValueReference> &vr, vector<fmi2Real> &ref) const = 0;

        virtual fmi2Status readString(const string &name, fmi2String &ref) const {
            const auto vr = getModelDescription().getVariableByName(name).valueReference;;
            return readString(vr, ref);
        }
        virtual fmi2Status readString(const fmi2ValueReference vr, fmi2String &ref) const = 0;
        virtual fmi2Status readString(const vector<fmi2ValueReference> &vr, vector<fmi2String> &ref) const = 0;

        virtual fmi2Status readBoolean(const string &name, fmi2Boolean &ref) const {
            const auto vr = getModelDescription().getVariableByName(name).valueReference;;
            return readBoolean(vr, ref);
        }
        virtual fmi2Status readBoolean(const fmi2ValueReference vr, fmi2Boolean &ref) const = 0;
        virtual fmi2Status readBoolean(const vector<fmi2ValueReference> &vr, vector<fmi2Boolean> &ref) const = 0;

        virtual ~FmuInstance() {};

    };

}

#endif //FMICPP_FMUINSTANCE_HPP
<|endoftext|>


<commit_before>/*
 * ValueContainerMessage.hpp
 *
 *  Created on: 18.04.2016
 *      Author: Marc Hartung
 */

#ifndef INCLUDE_MESSAGES_VALUECONTAINERMESSAGE_HPP_
#define INCLUDE_MESSAGES_VALUECONTAINERMESSAGE_HPP_

#include "AbstractMessage.hpp"
#include "../network_impl/SimNetworkFunctions.hpp"
#include "../VariableList.hpp"
#include "../ValueContainer.hpp"

namespace NetOff
{

    template<typename Specifyer>
    class ValueContainerMessage : public AbstractMessage<Specifyer>
    {
     public:

        ValueContainerMessage(const int & simId, const VariableList & vars, const Specifyer & spec)
                : AbstractMessage<Specifyer>(spec),
                  _data(nullptr),
                  _dataSize(0),
                  _spec(nullptr),
                  _id(nullptr),
                  _time(nullptr),
                  _container()
        {
            _dataSize = sizeof(Specifyer) + sizeof(int) + sizeof(double)
                    + ValueContainer::calcDataSize(vars.getReals().size(), vars.getInts().size(), vars.getBools().size());
            _data = std::shared_ptr<char>(new char[_dataSize]);
            char * p = _data.get();
            _spec = reinterpret_cast<Specifyer *>(p);
            p = saveShiftIntegralInData<Specifyer>(spec, p);
            _id = reinterpret_cast<int *>(p);
            p = saveShiftIntegralInData(simId, p);
            _time = reinterpret_cast<double *>(p);
            p = saveShiftIntegralInData<double>(0.0,p);
            _container = ValueContainer(_data, p, vars.getReals().size(), vars.getInts().size(), vars.getBools().size(),simId);
        }

        ValueContainerMessage()
                : AbstractMessage<Specifyer>(),
                  _data(std::shared_ptr<char>(new char[_dataSize])),
                  _dataSize(0),
                  _spec(nullptr),
                  _id(nullptr),
                  _time(nullptr),
                  _container()
        {

        }

        ValueContainer & getContainer()
        {
            return _container;
        }

        const ValueContainer & getContainer() const
        {
            return _container;
        }

        void setTime(const double & time)
        {
            *_time = time;
        }

        void setSpecifyer(const Specifyer & spec)
        {
            *_spec = spec;
        }

        const int & getId() const
        {
            return *_id;
        }

        const double & getTime() const
        {
            return *_time;
        }

        const Specifyer getSpecifyer() const
        {
            return *_spec;
        }

        char * data() override
        {
            return _data.get();
        }

        const char * data() const override
        {
            return _data.get();
        }

        size_t dataSize() const override
        {
            return _dataSize;
        }

     private:

        std::shared_ptr<char> _data;
        size_t _dataSize;

        Specifyer * _spec;
        int * _id;
        double * _time;

        ValueContainer _container;

    };
}

#endif /* INCLUDE_MESSAGES_VALUECONTAINERMESSAGE_HPP_ */
<commit_msg>Fix memory bug<commit_after>/*
 * ValueContainerMessage.hpp
 *
 *  Created on: 18.04.2016
 *      Author: Marc Hartung
 */

#ifndef INCLUDE_MESSAGES_VALUECONTAINERMESSAGE_HPP_
#define INCLUDE_MESSAGES_VALUECONTAINERMESSAGE_HPP_

#include "AbstractMessage.hpp"
#include "../network_impl/SimNetworkFunctions.hpp"
#include "../VariableList.hpp"
#include "../ValueContainer.hpp"

namespace NetOff
{

    template<typename Specifyer>
    class ValueContainerMessage : public AbstractMessage<Specifyer>
    {
     public:

        ValueContainerMessage(const int & simId, const VariableList & vars, const Specifyer & spec)
                : AbstractMessage<Specifyer>(spec),
                  _data(nullptr),
                  _dataSize(0),
                  _spec(nullptr),
                  _id(nullptr),
                  _time(nullptr),
                  _container()
        {
            _dataSize = sizeof(Specifyer) + sizeof(int) + sizeof(double)
                    + ValueContainer::calcDataSize(vars.getReals().size(), vars.getInts().size(), vars.getBools().size());
            _data = std::shared_ptr<char>(new char[_dataSize]);
            char * p = _data.get();
            _spec = reinterpret_cast<Specifyer *>(p);
            p = saveShiftIntegralInData<Specifyer>(spec, p);
            _id = reinterpret_cast<int *>(p);
            p = saveShiftIntegralInData(simId, p);
            _time = reinterpret_cast<double *>(p);
            p = saveShiftIntegralInData<double>(0.0,p);
            _container = ValueContainer(_data, p, vars.getReals().size(), vars.getInts().size(), vars.getBools().size(),simId);
        }

        ValueContainerMessage()
                : AbstractMessage<Specifyer>(),
                  _data(nullptr),
                  _dataSize(0),
                  _spec(nullptr),
                  _id(nullptr),
                  _time(nullptr),
                  _container()
        {
            _data = std::shared_ptr<char>(new char[_dataSize]);
        }

        ValueContainer & getContainer()
        {
            return _container;
        }

        const ValueContainer & getContainer() const
        {
            return _container;
        }

        void setTime(const double & time)
        {
            *_time = time;
        }

        void setSpecifyer(const Specifyer & spec)
        {
            *_spec = spec;
        }

        const int & getId() const
        {
            return *_id;
        }

        const double & getTime() const
        {
            return *_time;
        }

        const Specifyer getSpecifyer() const
        {
            return *_spec;
        }

        char * data() override
        {
            return _data.get();
        }

        const char * data() const override
        {
            return _data.get();
        }

        size_t dataSize() const override
        {
            return _dataSize;
        }

     private:

        std::shared_ptr<char> _data;
        size_t _dataSize;

        Specifyer * _spec;
        int * _id;
        double * _time;

        ValueContainer _container;

    };
}

#endif /* INCLUDE_MESSAGES_VALUECONTAINERMESSAGE_HPP_ */
<|endoftext|>


<commit_before>#ifndef VSMC_UTILITY_ALIGNED_ALLOCATOR
#define VSMC_UTILITY_ALIGNED_ALLOCATOR

#include <vsmc/internal/common.hpp>
#include <memory>

namespace vsmc {

namespace internal {

#if defined(__APPLE__) || defined(__MACOSX)
#if VSMC_MAC_VERSION_MIN_REQUIRED(VSMC_MAC_10_5)
/// \brief Use POSIX posix_memalign
/// \ingroup Config
#ifndef VSMC_USE_POSIX_MEMALIGN
#define VSMC_USE_POSIX_MEMALIGN 1
#endif
#endif // VSMC_MAC_VERSION_MIN_REQUIRED(VSMC_MAC_10_5)
#elif defined(__linux__)
#include <features.h>
#if defined(_POSIX_C_SOURCE) &&  _POSIX_C_SOURCE >= 200112L
#ifndef VSMC_USE_POSIX_MEMALIGN
#define VSMC_USE_POSIX_MEMALIGN 1
#endif
#endif // defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L
#if defined(_XOPEN_SOURCE) &&  _XOPEN_SOURCE >= 600
#ifndef VSMC_USE_POSIX_MEMALIGN
#define VSMC_USE_POSIX_MEMALIGN 1
#endif
#endif // defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 600
#endif

#ifndef VSMC_USE_POSIX_MEMALIGN
#define VSMC_USE_POSIX_MEMALIGN 0
#endif

#if VSMC_USE_POSIX_MEMALIGN

inline void *aligned_malloc (std::size_t n, std::size_t alignment)
{
    void *ptr;
    if (posix_memalign(&ptr, alignment, n) != 0)
        throw std::bad_alloc();

    return ptr;
}

inline void aligned_free (void *ptr) {free(ptr);}

#elif VSMC_USE_MKL

#include <mkl_service.h>

inline void *aligned_malloc (std::size_t n, std::size_t alignment)
{return mkl_malloc(n, static_cast<int>(alignment));}

inline void aligned_free (void *ptr) {mkl_free(ptr);}

#elif defined(_WIN32)

#include <malloc.h>

inline void *aligned_malloc (std::size_t n, std::size_t alignment)
{return _aligned_malloc(n, alignment);}

inline void aligned_free (void *ptr) {aligned_free(ptr);}

#else

#error Aligned allocation not implemented

#endif // VSMC_USE_POSIX_MEMALIGN

} // namespace vsmc::internal

template <typename T, std::size_t Alignment>
class AlignedAllocator
{
    public :

    typedef T value_type;
    typedef T * pointer;
    typedef const T * const_pointer;
    typedef T & reference;
    typedef const T & const_reference;
    typedef std::size_t size_type;
    typedef std::ptrdiff_t difference_type;
    typedef cxx11::true_type propagate_on_container_move_assignment;

    template <typename U> struct rebind
    {typedef AlignedAllocator<U, Alignment> other;};

    AlignedAllocator () {}

    AlignedAllocator (const AlignedAllocator<T, Alignment> &) {}

    template <typename U>
    AlignedAllocator (const AlignedAllocator<U, Alignment> &) {}

    ~AlignedAllocator () {}

    static VSMC_CONSTEXPR size_type max_size ()
    {return static_cast<size_type>(~static_cast<size_type>(0)) / sizeof(T);}

    static pointer address (reference obj)
    {return std::addressof(obj);}

    static const_pointer address (const_reference obj)
    {return std::addressof(obj);}

    static pointer allocate (size_type n, const void * = VSMC_NULLPTR)
    {
        if (n == 0)
            return VSMC_NULLPTR;

        return static_cast<pointer>(
                internal::aligned_malloc(sizeof(T) * n, Alignment));
    }

    static void deallocate (pointer ptr, size_type n)
    {
        if (n == 0)
            return;

        internal::aligned_free(ptr);
    }

#if VSMC_HAS_CXX11_RVALUE_REFERENCES && VSMC_HAS_CXX11_VARIADIC_TEMPLATES
    template <typename U, typename... Args>
    static void construct (pointer ptr, Args &&... args)
    {
        ::new (const_cast<void *>(static_cast<const volatile void *>(ptr)))
            U(std::forward<Args>(args)...)
    }
#else
    static void construct (pointer ptr, const_reference val)
    {new (const_cast<void *>(static_cast<const volatile void *>(ptr))) T(val);}
#endif

    static void destory (pointer ptr) {ptr->~T();}

    friend bool operator== (
            const AlignedAllocator<T, Alignment> &,
            const AlignedAllocator<T, Alignment> &)
    {return true;}

    friend bool operator!= (
            const AlignedAllocator<T, Alignment> &alloc1,
            const AlignedAllocator<T, Alignment> &alloc2)
    {return !(alloc1 == alloc2);}
}; // class AlignedAllocator

} // namespace vsmc

#endif // VSMC_UTILITY_ALIGNED_ALLOCATOR
<commit_msg>fix allocator<commit_after>#ifndef VSMC_UTILITY_ALIGNED_ALLOCATOR
#define VSMC_UTILITY_ALIGNED_ALLOCATOR

#include <vsmc/internal/common.hpp>
#include <memory>

namespace vsmc {

namespace internal {

#if defined(__APPLE__) || defined(__MACOSX)
#if VSMC_MAC_VERSION_MIN_REQUIRED(VSMC_MAC_10_5)
/// \brief Use POSIX posix_memalign
/// \ingroup Config
#ifndef VSMC_USE_POSIX_MEMALIGN
#define VSMC_USE_POSIX_MEMALIGN 1
#endif
#endif // VSMC_MAC_VERSION_MIN_REQUIRED(VSMC_MAC_10_5)
#elif defined(__linux__)
#include <features.h>
#if defined(_POSIX_C_SOURCE) &&  _POSIX_C_SOURCE >= 200112L
#ifndef VSMC_USE_POSIX_MEMALIGN
#define VSMC_USE_POSIX_MEMALIGN 1
#endif
#endif // defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L
#if defined(_XOPEN_SOURCE) &&  _XOPEN_SOURCE >= 600
#ifndef VSMC_USE_POSIX_MEMALIGN
#define VSMC_USE_POSIX_MEMALIGN 1
#endif
#endif // defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 600
#endif

#ifndef VSMC_USE_POSIX_MEMALIGN
#define VSMC_USE_POSIX_MEMALIGN 0
#endif

#if VSMC_USE_POSIX_MEMALIGN

inline void *aligned_malloc (std::size_t n, std::size_t alignment)
{
    void *ptr;
    if (posix_memalign(&ptr, alignment, n) != 0)
        throw std::bad_alloc();

    return ptr;
}

inline void aligned_free (void *ptr) {free(ptr);}

#elif VSMC_USE_MKL

#include <mkl_service.h>

inline void *aligned_malloc (std::size_t n, std::size_t alignment)
{return mkl_malloc(n, static_cast<int>(alignment));}

inline void aligned_free (void *ptr) {mkl_free(ptr);}

#elif defined(_WIN32)

#include <malloc.h>

inline void *aligned_malloc (std::size_t n, std::size_t alignment)
{return _aligned_malloc(n, alignment);}

inline void aligned_free (void *ptr) {aligned_free(ptr);}

#else

#error Aligned allocation not implemented

#endif // VSMC_USE_POSIX_MEMALIGN

} // namespace vsmc::internal

template <typename T, std::size_t Alignment>
class AlignedAllocator
{
    public :

    typedef T value_type;
    typedef T * pointer;
    typedef const T * const_pointer;
    typedef T & reference;
    typedef const T & const_reference;
    typedef std::size_t size_type;
    typedef std::ptrdiff_t difference_type;
    typedef cxx11::true_type propagate_on_container_move_assignment;

    template <typename U> struct rebind
    {typedef AlignedAllocator<U, Alignment> other;};

    AlignedAllocator () {}

    AlignedAllocator (const AlignedAllocator<T, Alignment> &) {}

    template <typename U>
    AlignedAllocator (const AlignedAllocator<U, Alignment> &) {}

    ~AlignedAllocator () {}

    static VSMC_CONSTEXPR size_type max_size ()
    {return static_cast<size_type>(~static_cast<size_type>(0)) / sizeof(T);}

    static pointer address (reference obj)
    {return std::addressof(obj);}

    static const_pointer address (const_reference obj)
    {return std::addressof(obj);}

    static pointer allocate (size_type n, const void * = VSMC_NULLPTR)
    {
        if (n == 0)
            return VSMC_NULLPTR;

        return static_cast<pointer>(
                internal::aligned_malloc(sizeof(T) * n, Alignment));
    }

    static void deallocate (pointer ptr, size_type n)
    {
        if (n == 0)
            return;

        internal::aligned_free(ptr);
    }

#if VSMC_HAS_CXX11_RVALUE_REFERENCES && VSMC_HAS_CXX11_VARIADIC_TEMPLATES
    template <typename U, typename... Args>
    static void construct (pointer ptr, Args &&... args)
    {
        ::new (const_cast<void *>(static_cast<const volatile void *>(ptr)))
            U(std::forward<Args>(args)...);
    }
#else
    static void construct (pointer ptr, const_reference val)
    {new (const_cast<void *>(static_cast<const volatile void *>(ptr))) T(val);}
#endif

    static void destory (pointer ptr) {ptr->~T();}

    friend bool operator== (
            const AlignedAllocator<T, Alignment> &,
            const AlignedAllocator<T, Alignment> &)
    {return true;}

    friend bool operator!= (
            const AlignedAllocator<T, Alignment> &alloc1,
            const AlignedAllocator<T, Alignment> &alloc2)
    {return !(alloc1 == alloc2);}
}; // class AlignedAllocator

} // namespace vsmc

#endif // VSMC_UTILITY_ALIGNED_ALLOCATOR
<|endoftext|>


<commit_before>/**
 * @file   llsdmessage_test.cpp
 * @author Nat Goodspeed
 * @date   2008-12-22
 * @brief  Test of llsdmessage.h
 *
 * $LicenseInfo:firstyear=2008&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2010, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#if LL_WINDOWS
#pragma warning (disable : 4675) // "resolved by ADL" -- just as I want!
#endif

// Precompiled header
#include "linden_common.h"
// associated header
#include "llsdmessage.h"
// STL headers
#include <iostream>
// std headers
#include <stdexcept>
#include <typeinfo>
// external library headers
// other Linden headers
#include "../test/lltut.h"
#include "llsdserialize.h"
#include "llevents.h"
#include "stringize.h"
#include "llhost.h"
#include "tests/networkio.h"
#include "tests/commtest.h"

/*****************************************************************************
*   TUT
*****************************************************************************/
namespace tut
{
    struct llsdmessage_data: public commtest_data
    {
        LLEventPump& httpPump;

        llsdmessage_data():
            httpPump(pumps.obtain("LLHTTPClient"))
        {
            LLSDMessage::link();
        }
    };
    typedef test_group<llsdmessage_data> llsdmessage_group;
    typedef llsdmessage_group::object llsdmessage_object;
    llsdmessage_group llsdmgr("llsdmessage");

    template<> template<>
    void llsdmessage_object::test<1>()
    {
        bool threw = false;
        // This should fail...
        try
        {
            LLSDMessage localListener;
        }
        catch (const LLEventPump::DupPumpName&)
        {
            threw = true;
        }
        catch (const std::runtime_error& ex)
        {
            // This clause is because on Linux, on the viewer side, for this
            // one test program (though not others!), the
            // LLEventPump::DupPumpName exception isn't caught by the clause
            // above. Warn the user...
            std::cerr << "Failed to catch " << typeid(ex).name() << std::endl;
            // But if the expected exception was thrown, allow the test to
            // succeed anyway. Not sure how else to handle this odd case.
            if (std::string(typeid(ex).name()) == typeid(LLEventPump::DupPumpName).name())
            {
                threw = true;
            }
            else
            {
                // We don't even recognize this exception. Let it propagate
                // out to TUT to fail the test.
                throw;
            }
        }
        catch (...)
        {
            std::cerr << "Utterly failed to catch expected exception!" << std::endl;
            // This case is full of fail. We HAVE to address it.
            throw;
        }
        ensure("second LLSDMessage should throw", threw);
    }

    template<> template<>
    void llsdmessage_object::test<2>()
    {
        LLSD request, body;
        body["data"] = "yes";
        request["payload"] = body;
        request["reply"] = replyPump.getName();
        request["error"] = errorPump.getName();
        bool threw = false;
        try
        {
            httpPump.post(request);
        }
        catch (const LLSDMessage::ArgError&)
        {
            threw = true;
        }
        ensure("missing URL", threw);
    }

    template<> template<>
    void llsdmessage_object::test<3>()
    {
        LLSD request, body;
        body["data"] = "yes";
        request["url"] = server + "got-message";
        request["payload"] = body;
        request["reply"] = replyPump.getName();
        request["error"] = errorPump.getName();
        httpPump.post(request);
        ensure("got response", netio.pump());
        ensure("success response", success);
        ensure_equals(result.asString(), "success");

        body["status"] = 499;
        body["reason"] = "custom error message";
        request["url"] = server + "fail";
        request["payload"] = body;
        httpPump.post(request);
        ensure("got response", netio.pump());
        ensure("failure response", ! success);
        ensure_equals(result["status"].asInteger(), body["status"].asInteger());
        ensure_equals(result["reason"].asString(),  body["reason"].asString());
    }
} // namespace tut
<commit_msg>SH-734 [REGRESSION] INTEGRATION_TEST_llsdmessage and _capabilitylistener failing in opensource environment<commit_after>/**
 * @file   llsdmessage_test.cpp
 * @author Nat Goodspeed
 * @date   2008-12-22
 * @brief  Test of llsdmessage.h
 *
 * $LicenseInfo:firstyear=2008&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2010, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#if LL_WINDOWS
#pragma warning (disable : 4675) // "resolved by ADL" -- just as I want!
#endif

// Precompiled header
#include "linden_common.h"
// associated header
#include "llsdmessage.h"
// STL headers
#include <iostream>
// std headers
#include <stdexcept>
#include <typeinfo>
// external library headers
// other Linden headers
#include "../test/lltut.h"
#include "llsdserialize.h"
#include "llevents.h"
#include "stringize.h"
#include "llhost.h"
#include "tests/networkio.h"
#include "tests/commtest.h"

/*****************************************************************************
*   TUT
*****************************************************************************/
namespace tut
{
    struct llsdmessage_data: public commtest_data
    {
        LLEventPump& httpPump;

        llsdmessage_data():
            httpPump(pumps.obtain("LLHTTPClient"))
        {
            LLCurl::initClass();
            LLSDMessage::link();
        }
    };
    typedef test_group<llsdmessage_data> llsdmessage_group;
    typedef llsdmessage_group::object llsdmessage_object;
    llsdmessage_group llsdmgr("llsdmessage");

    template<> template<>
    void llsdmessage_object::test<1>()
    {
        bool threw = false;
        // This should fail...
        try
        {
            LLSDMessage localListener;
        }
        catch (const LLEventPump::DupPumpName&)
        {
            threw = true;
        }
        catch (const std::runtime_error& ex)
        {
            // This clause is because on Linux, on the viewer side, for this
            // one test program (though not others!), the
            // LLEventPump::DupPumpName exception isn't caught by the clause
            // above. Warn the user...
            std::cerr << "Failed to catch " << typeid(ex).name() << std::endl;
            // But if the expected exception was thrown, allow the test to
            // succeed anyway. Not sure how else to handle this odd case.
            if (std::string(typeid(ex).name()) == typeid(LLEventPump::DupPumpName).name())
            {
                threw = true;
            }
            else
            {
                // We don't even recognize this exception. Let it propagate
                // out to TUT to fail the test.
                throw;
            }
        }
        catch (...)
        {
            std::cerr << "Utterly failed to catch expected exception!" << std::endl;
            // This case is full of fail. We HAVE to address it.
            throw;
        }
        ensure("second LLSDMessage should throw", threw);
    }

    template<> template<>
    void llsdmessage_object::test<2>()
    {
        LLSD request, body;
        body["data"] = "yes";
        request["payload"] = body;
        request["reply"] = replyPump.getName();
        request["error"] = errorPump.getName();
        bool threw = false;
        try
        {
            httpPump.post(request);
        }
        catch (const LLSDMessage::ArgError&)
        {
            threw = true;
        }
        ensure("missing URL", threw);
    }

    template<> template<>
    void llsdmessage_object::test<3>()
    {
        LLSD request, body;
        body["data"] = "yes";
        request["url"] = server + "got-message";
        request["payload"] = body;
        request["reply"] = replyPump.getName();
        request["error"] = errorPump.getName();
        httpPump.post(request);
        ensure("got response", netio.pump());
        ensure("success response", success);
        ensure_equals(result.asString(), "success");

        body["status"] = 499;
        body["reason"] = "custom error message";
        request["url"] = server + "fail";
        request["payload"] = body;
        httpPump.post(request);
        ensure("got response", netio.pump());
        ensure("failure response", ! success);
        ensure_equals(result["status"].asInteger(), body["status"].asInteger());
        ensure_equals(result["reason"].asString(),  body["reason"].asString());
    }
} // namespace tut
<|endoftext|>