text:
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

#include "stdafx.h"

#include <boost/test/unit_test.hpp>
#include "Common/boost-taef.h"

namespace TransportUnitTest
{
    using namespace std;
    using namespace Common;
    using namespace Transport;

    class TestClient : public enable_shared_from_this<TestClient>
    {
        DENY_COPY(TestClient)

    public:

        TestClient()
        {
        }

        shared_ptr<AsyncOperation> BeginSendRequest(
            MessageUPtr && message,
            string const &,
            TimeSpan const & timeout,
            AsyncCallback const & callback,
            Common::AsyncOperationSPtr const & parent)
        {
            MessageId id = message->MessageId;

            auto operation = make_shared<RequestAsyncOperation>(
                this->table_,
                id,
                timeout,
                callback,
                parent);
            operation->Start(operation);

            auto error = this->table_.TryInsertEntry(id, operation);
            if (error.IsSuccess())
            {
                if (operation->IsCompleted)
                {
                    // If there was a racing and we added to the table after OnComplete ran,
                    // we must remove it again since it will not itself.
                    this->table_.TryRemoveEntry(id, operation);
                }
            }
            else
            {
                operation->TryComplete(operation, error);
            }

            return operation;
        }

        ErrorCode EndSendRequest(shared_ptr<AsyncOperation> const & operation, MessageUPtr & message)
        {
            return RequestAsyncOperation::End(operation, message);
        }

        void CompleteRequest(MessageId const & messageId)
        {
            RequestAsyncOperationSPtr operation;
            if (this->table_.TryRemoveEntry(messageId, operation))
            {
                // we removed it from the table so complete with a reply message
                VERIFY_IS_TRUE(operation);

                operation->SetReply(make_unique<Message>());
                operation->TryComplete(operation, ErrorCode());
            }
            else
            {
                VERIFY_IS_TRUE(!operation);
            }
        }

        void Close()
        {
            this->table_.Close();
        }

    private:
        RequestTable table_;
    };

    BOOST_AUTO_TEST_SUITE2(RequestTableTests)

    BOOST_AUTO_TEST_CASE(BasicTest)
    {
        TestClient siteNode;
        vector<MessageId> messageIds;

        for (int i = 0; i < 10; ++i)
        {
            auto request = make_unique<Message>();
            request->Headers.Add(MessageIdHeader());

            messageIds.push_back(request->MessageId);

            auto result = siteNode.BeginSendRequest(std::move(request), "localhost", TimeSpan::FromSeconds(5),
                [&siteNode](AsyncOperationSPtr contextSPtr) -> void
                {
                    MessageUPtr resultSPtr;
                    ErrorCode error = siteNode.EndSendRequest(contextSPtr, resultSPtr);

                    Trace.WriteInfo(TraceType, "Success = {0}", error.IsSuccess());
                    Trace.WriteInfo(TraceType, "result = '{0}'", (resultSPtr ? "no message" : "message"));
                },
                AsyncOperationSPtr());
        }

        for(MessageId const & id : messageIds)
        {
            siteNode.CompleteRequest(id);
        }
    }

    BOOST_AUTO_TEST_CASE(BasicTest2)
    {
        auto siteNode = make_shared<TestClient>();
        auto request = make_unique<Message>();

        // create a message
        request->Headers.Add(MessageIdHeader());

        auto result = siteNode->BeginSendRequest(std::move(request), "localhost", TimeSpan::FromSeconds(5),
            [](AsyncOperationSPtr contextSPtr) -> void
            {
                auto callbackSiteNode = AsyncOperationRoot<std::shared_ptr<TestClient> >::Get(contextSPtr->Parent);

                MessageUPtr resultSPtr;
                ErrorCode error = callbackSiteNode->EndSendRequest(contextSPtr, resultSPtr);

                Trace.WriteInfo(TraceType, "Success = {0}", error.IsSuccess());
                Trace.WriteInfo(TraceType, "result = '{0}'", (resultSPtr ? "no message" : "message"));
            },
            AsyncOperationRoot<std::shared_ptr<TestClient> >::Create(siteNode)
            );

        siteNode->CompleteRequest(request->MessageId);
    }

    BOOST_AUTO_TEST_CASE(BasicAsyncTest)
    {
        TestClient siteNode;
        auto request = make_unique<Message>();

        // create a message
        request->Headers.Add(MessageIdHeader());
        auto id = request->MessageId;

        ManualResetEvent callbackFired(false);

        auto result = siteNode.BeginSendRequest(std::move(request), "localhost", TimeSpan::FromSeconds(5),
            [&siteNode, &callbackFired](AsyncOperationSPtr contextSPtr) -> void
            {
                MessageUPtr resultSPtr;
                ErrorCode error = siteNode.EndSendRequest(contextSPtr, resultSPtr);

                Trace.WriteInfo(TraceType, "Success = {0}", error.IsSuccess());
                Trace.WriteInfo(TraceType, "result = '{0}'", (resultSPtr ? "no message" : "message"));

                callbackFired.Set();
            }, AsyncOperationSPtr());

        Threadpool::Post(
            [&siteNode, id]() -> void
            {
                siteNode.CompleteRequest(id);
            });

        VERIFY_IS_TRUE(callbackFired.WaitOne(TimeSpan::FromSeconds(10)));
    }

    BOOST_AUTO_TEST_CASE(TimeoutTest)
    {
        TestClient siteNode;
        auto request = make_unique<Message>();

        // create a message
        request->Headers.Add(MessageIdHeader());

        ManualResetEvent callbackFired(false);
        Stopwatch timer;
        timer.Start();

        auto result = siteNode.BeginSendRequest(std::move(request), "localhost", TimeSpan::FromSeconds(2),
            [&siteNode, &callbackFired](AsyncOperationSPtr contextSPtr) -> void
            {
                MessageUPtr resultSPtr;
                ErrorCode error = siteNode.EndSendRequest(contextSPtr, resultSPtr);

                VERIFY_IS_TRUE(error.ReadValue() == ErrorCodeValue::Timeout);
                Trace.WriteInfo(TraceType, "result = '{0}'", (resultSPtr ? "no message" : "message"));

                callbackFired.Set();
            }, AsyncOperationSPtr());

        VERIFY_IS_TRUE(callbackFired.WaitOne(TimeSpan::FromSeconds(10)));
        timer.Stop();

        Trace.WriteInfo(TraceType, "Elapesed: {0}", timer.Elapsed.TotalMilliseconds());
        VERIFY_IS_TRUE(timer.Elapsed > TimeSpan::FromSeconds(1.5));
    }

    BOOST_AUTO_TEST_CASE(CloseTest)
    {
        TestClient siteNode;
        auto request = make_unique<Message>();

        // create a message
        request->Headers.Add(MessageIdHeader());

        ManualResetEvent callbackFired(false);

        siteNode.Close();

        auto result = siteNode.BeginSendRequest(std::move(request), "localhost", TimeSpan::FromSeconds(2),
            [&siteNode, &callbackFired](AsyncOperationSPtr contextSPtr) -> void
            {
                MessageUPtr resultSPtr;
                ErrorCode error = siteNode.EndSendRequest(contextSPtr, resultSPtr);

                VERIFY_IS_TRUE(error.ReadValue() == ErrorCodeValue::ObjectClosed);
                Trace.WriteInfo(TraceType, "result = '{0}'", (resultSPtr ? "no message" : "message"));

                callbackFired.Set();
            }, AsyncOperationSPtr());

        VERIFY_IS_TRUE(callbackFired.WaitOne(TimeSpan::FromSeconds(5)));
    }

    BOOST_AUTO_TEST_SUITE_END()
}

max_stars_repo_name: leikong/service-fabric

max_issues_repo_name: leikong/service-fabric

max_forks_repo_name: leikong/service-fabric


text:
#include "action.hpp"

#include <vector>

#include "exceptions.hpp"
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/log/trivial.hpp>

namespace ImageProcessor {

Initialise::Initialise(IFilesystem *fs, std::string const input_file,
                       std::string const output_folder)
    : fs_{std::move(fs)}, input_file_{input_file}, output_folder_{
                                                       output_folder} {
  action_ = "initialise";
  if (input_file_ == "")
    throw ImageProcessorError("Input file not specified.");
  if (output_folder_ == "")
    throw ImageProcessorError("Output folder not specified.");
  if (fs_ == nullptr)
    throw ImageProcessorError("fs not a valid pointer");
}

Image Initialise::process(Image image) {
  BOOST_LOG_TRIVIAL(debug) << "Initial setup before processing image actions";
  BOOST_LOG_TRIVIAL(debug) << "File path: " << input_file_
                           << ". Output folder: " << output_folder_;
  if (fs_->path_exists(output_folder_)) {
    fs_->remove_folder(output_folder_);
  }
  fs_->create_folders(output_folder_);
  image = Image{fs_->read_image(input_file_, false),
                boost::filesystem::path(input_file_).filename().string(),
                output_folder_};
  return image;
}

Save::Save(IFilesystem *fs, std::string const filename)
    : fs_{std::move(fs)}, filename_{filename} {
  action_ = "save";
  if (fs_ == nullptr)
    throw ImageProcessorError("fs not a valid pointer");
}

int Save::counter_ = 0;

// image is written to disk based on the filename supplied.
// User defined name is preferred otherwise the name is constructed.
// Constructed filename is based on the image name appended with
// the number of times the image has been saved when > 1.
Image Save::process(Image image) {
  BOOST_LOG_TRIVIAL(debug) << "Saving image";
  // counter is incremented per save so that the filename is consistent
  // independent on whether the user enters a name or not
  counter_++;
  process_filename(image.filename_);
  prefix_folder(image.output_folder_);
  if (fs_->write_image(path_, image))
    return image;
  throw ImageProcessorError("Writing to file failed.");
}

// Constructs save file name (filename_).
// if not user defined, one is created
// extension is applied if missing from in the incoming image.
void Save::process_filename(boost::filesystem::path const image_filename) {
  if (filename_.empty())
    build_custom_filename(image_filename);
  else
    path_ = filename_;
  if (!path_.has_extension())
    path_.replace_extension(image_filename.extension());
}

// if filename was not set by user it is created based on the image filename
// Filename constructed based on image filename and and an increment defined by
// the save number. First save has no suffix.
// Each subsequent save results in appending _X (where X is a number) to the
// filename.
void Save::build_custom_filename(boost::filesystem::path const image_filename) {
  if (counter_ == 1) {
    path_ = image_filename;
  } else {
    std::string file_string =
        image_filename.stem().string() + "_" + std::to_string(counter_);
    path_ = boost::filesystem::path{file_string};
  }
}

// Output path based on folder and filename.
// Base path folder is the project working directory
std::string Save::prefix_folder(std::string const folder) {
  boost::filesystem::path output{folder};
  path_ = output / path_;
}

Grey::Grey(IOpenCV *i_opencv) : cv_{std::move(i_opencv)} {
  action_ = "grey";
  if (cv_ == nullptr)
    throw ImageProcessorError("fs not a valid pointer");
}

Image Grey::process(Image image) {
  BOOST_LOG_TRIVIAL(debug) << "Converting to greyscale";
  Image output = cv_->grey(image);
  return output;
}
} // namespace ImageProcessor

ext: cpp


text:
/**********************************************************************
 *  Copyright (c) 2008-2015, Alliance for Sustainable Energy.
 *  All rights reserved.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  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
 **********************************************************************/

#include "UtilityCost_Variable.hpp"
#include "UtilityCost_Variable_Impl.hpp"

#include "Model_Impl.hpp"

#include <utilities/idd/OS_UtilityCost_Variable_FieldEnums.hxx>
#include <utilities/idd/IddEnums.hxx>

#include "../utilities/core/Assert.hpp"

#include <boost/algorithm/string.hpp>

namespace openstudio {
namespace model  {
namespace detail {

UtilityCost_Variable_Impl::UtilityCost_Variable_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle)
  : ParentObject_Impl(idfObject, model, keepHandle)
{
  OS_ASSERT(idfObject.iddObject().type() == UtilityCost_Variable::iddObjectType());
}

UtilityCost_Variable_Impl::UtilityCost_Variable_Impl(const openstudio::detail::WorkspaceObject_Impl& other,
                                           Model_Impl* model,
                                           bool keepHandle)
  : ParentObject_Impl(other,model,keepHandle)
{
  OS_ASSERT(other.iddObject().type() == UtilityCost_Variable::iddObjectType());
}

UtilityCost_Variable_Impl::UtilityCost_Variable_Impl(const UtilityCost_Variable_Impl& other,Model_Impl* model,bool keepHandle)
  : ParentObject_Impl(other,model,keepHandle)
{
}

OptionalDouble UtilityCost_Variable_Impl::januaryValue() const
{
  return getDouble(OS_UtilityCost_VariableFields::JanuaryValue);
}

void UtilityCost_Variable_Impl::setJanuaryValue(double num)
{
  setDouble(OS_UtilityCost_VariableFields::JanuaryValue,num);
}

OptionalDouble UtilityCost_Variable_Impl::februaryValue() const
{
  return getDouble(OS_UtilityCost_VariableFields::FebruaryValue);
}

void UtilityCost_Variable_Impl::setFebruaryValue(double num)
{
  setDouble(OS_UtilityCost_VariableFields::FebruaryValue,num);
}

OptionalDouble UtilityCost_Variable_Impl::marchValue() const
{
  return getDouble(OS_UtilityCost_VariableFields::MarchValue);
}

void UtilityCost_Variable_Impl::setMarchValue(double num)
{
  setDouble(OS_UtilityCost_VariableFields::MarchValue,num);
}

OptionalDouble UtilityCost_Variable_Impl::aprilValue() const
{
  return getDouble(OS_UtilityCost_VariableFields::AprilValue);
}

void UtilityCost_Variable_Impl::setAprilValue(double num)
{
  setDouble(OS_UtilityCost_VariableFields::AprilValue,num);
}

OptionalDouble UtilityCost_Variable_Impl::mayValue() const
{
  return getDouble(OS_UtilityCost_VariableFields::MayValue);
}

void UtilityCost_Variable_Impl::setMayValue(double num)
{
  setDouble(OS_UtilityCost_VariableFields::MayValue,num);
}

OptionalDouble UtilityCost_Variable_Impl::juneValue() const
{
  return getDouble(OS_UtilityCost_VariableFields::JuneValue);
}

void UtilityCost_Variable_Impl::setJuneValue(double num)
{
  setDouble(OS_UtilityCost_VariableFields::JuneValue,num);
}

OptionalDouble UtilityCost_Variable_Impl::julyValue() const
{
  return getDouble(OS_UtilityCost_VariableFields::JulyValue);
}

void UtilityCost_Variable_Impl::setJulyValue(double num)
{
  setDouble(OS_UtilityCost_VariableFields::JulyValue,num);
}

OptionalDouble UtilityCost_Variable_Impl::augustValue() const
{
  return getDouble(OS_UtilityCost_VariableFields::AugustValue);
}

void UtilityCost_Variable_Impl::setAugustValue(double num)
{
  setDouble(OS_UtilityCost_VariableFields::AugustValue,num);
}

OptionalDouble UtilityCost_Variable_Impl::septemberValue() const
{
  return getDouble(OS_UtilityCost_VariableFields::SeptemberValue);
}

void UtilityCost_Variable_Impl::setSeptemberValue(double num)
{
  setDouble(OS_UtilityCost_VariableFields::SeptemberValue,num);
}

OptionalDouble UtilityCost_Variable_Impl::octoberValue() const
{
  return getDouble(OS_UtilityCost_VariableFields::OctoberValue);
}

void UtilityCost_Variable_Impl::setOctoberValue(double num)
{
  setDouble(OS_UtilityCost_VariableFields::OctoberValue,num);
}

OptionalDouble UtilityCost_Variable_Impl::novemberValue() const
{
  return getDouble(OS_UtilityCost_VariableFields::NovemberValue);
}

void UtilityCost_Variable_Impl::setNovemberValue(double num)
{
  setDouble(OS_UtilityCost_VariableFields::NovemberValue,num);
}

OptionalDouble UtilityCost_Variable_Impl::decemberValue() const
{
  return getDouble(OS_UtilityCost_VariableFields::DecemberValue);
}

void UtilityCost_Variable_Impl::setDecemberValue(double num)
{
  setDouble(OS_UtilityCost_VariableFields::DecemberValue,num);
}

OptionalString UtilityCost_Variable_Impl::tariffName() const
{
  return getString(OS_UtilityCost_VariableFields::TariffName);
}

void UtilityCost_Variable_Impl::setTariffName(const std::string& str)
{
  setString(OS_UtilityCost_VariableFields::TariffName,str);
}

OptionalString UtilityCost_Variable_Impl::variableType() const
{
  return getString(OS_UtilityCost_VariableFields::VariableType);
}

void UtilityCost_Variable_Impl::setVariableType(const std::string& str)
{
  setString(OS_UtilityCost_VariableFields::VariableType,str);
}

// return the parent object in the hierarchy
boost::optional<ParentObject> UtilityCost_Variable_Impl::parent() const
{
  return boost::optional<ParentObject>();
}

// set the parent, child may have to call methods on the parent
bool UtilityCost_Variable_Impl::setParent(ParentObject& newParent)
{
  //if (newParent.optionalCast<SomeParentClass>() && (newParent.model() == model())) {
  //  return true;
  //}
  return false;
}

// return any children objects in the hierarchy
std::vector<ModelObject> UtilityCost_Variable_Impl::children() const
{
  std::vector<ModelObject> result;
  return result;
}

std::vector<IddObjectType> UtilityCost_Variable_Impl::allowableChildTypes() const {
  IddObjectTypeVector result;
  return result;
}

// Get all output variable names that could be associated with this object.
const std::vector<std::string>& UtilityCost_Variable_Impl::outputVariableNames() const
{
  static std::vector<std::string> result;
  if (result.empty()){
  }
  return result;
}

} // detail

/// constructor
UtilityCost_Variable::UtilityCost_Variable(const Model& model)
  : ParentObject(UtilityCost_Variable::iddObjectType(),model)
{
  OS_ASSERT(getImpl<detail::UtilityCost_Variable_Impl>());
}

// constructor
UtilityCost_Variable::UtilityCost_Variable(std::shared_ptr<detail::UtilityCost_Variable_Impl> impl)
  : ParentObject(impl)
{}

OptionalDouble UtilityCost_Variable::januaryValue() const
{
  return getImpl<detail::UtilityCost_Variable_Impl>()->januaryValue();
}

void UtilityCost_Variable::setJanuaryValue(double num)
{
  getImpl<detail::UtilityCost_Variable_Impl>()->setJanuaryValue(num);
}

OptionalDouble UtilityCost_Variable::februaryValue() const
{
  return getImpl<detail::UtilityCost_Variable_Impl>()->februaryValue();
}

void UtilityCost_Variable::setFebruaryValue(double num)
{
  getImpl<detail::UtilityCost_Variable_Impl>()->setFebruaryValue(num);
}

OptionalDouble UtilityCost_Variable::marchValue() const
{
  return getImpl<detail::UtilityCost_Variable_Impl>()->marchValue();
}

void UtilityCost_Variable::setMarchValue(double num)
{
  getImpl<detail::UtilityCost_Variable_Impl>()->setMarchValue(num);
}

OptionalDouble UtilityCost_Variable::aprilValue() const
{
  return getImpl<detail::UtilityCost_Variable_Impl>()->aprilValue();
}

void UtilityCost_Variable::setAprilValue(double num)
{
  getImpl<detail::UtilityCost_Variable_Impl>()->setAprilValue(num);
}

OptionalDouble UtilityCost_Variable::mayValue() const
{
  return getImpl<detail::UtilityCost_Variable_Impl>()->mayValue();
}

void UtilityCost_Variable::setMayValue(double num)
{
  getImpl<detail::UtilityCost_Variable_Impl>()->setMayValue(num);
}

OptionalDouble UtilityCost_Variable::juneValue() const
{
  return getImpl<detail::UtilityCost_Variable_Impl>()->juneValue();
}

void UtilityCost_Variable::setJuneValue(double num)
{
  getImpl<detail::UtilityCost_Variable_Impl>()->setJuneValue(num);
}

OptionalDouble UtilityCost_Variable::julyValue() const
{
  return getImpl<detail::UtilityCost_Variable_Impl>()->julyValue();
}

void UtilityCost_Variable::setJulyValue(double num)
{
  getImpl<detail::UtilityCost_Variable_Impl>()->setJulyValue(num);
}

OptionalDouble UtilityCost_Variable::augustValue() const
{
  return getImpl<detail::UtilityCost_Variable_Impl>()->augustValue();
}

void UtilityCost_Variable::setAugustValue(double num)
{
  getImpl<detail::UtilityCost_Variable_Impl>()->setAugustValue(num);
}

OptionalDouble UtilityCost_Variable::septemberValue() const
{
  return getImpl<detail::UtilityCost_Variable_Impl>()->septemberValue();
}

void UtilityCost_Variable::setSeptemberValue(double num)
{
  getImpl<detail::UtilityCost_Variable_Impl>()->setSeptemberValue(num);
}

OptionalDouble UtilityCost_Variable::octoberValue() const
{
  return getImpl<detail::UtilityCost_Variable_Impl>()->octoberValue();
}

void UtilityCost_Variable::setOctoberValue(double num)
{
  getImpl<detail::UtilityCost_Variable_Impl>()->setOctoberValue(num);
}

OptionalDouble UtilityCost_Variable::novemberValue() const
{
  return getImpl<detail::UtilityCost_Variable_Impl>()->novemberValue();
}

void UtilityCost_Variable::setNovemberValue(double num)
{
  getImpl<detail::UtilityCost_Variable_Impl>()->setNovemberValue(num);
}

OptionalDouble UtilityCost_Variable::decemberValue() const
{
  return getImpl<detail::UtilityCost_Variable_Impl>()->decemberValue();
}

void UtilityCost_Variable::setDecemberValue(double num)
{
  getImpl<detail::UtilityCost_Variable_Impl>()->setDecemberValue(num);
}

OptionalString UtilityCost_Variable::name() const
{
  return getImpl<detail::UtilityCost_Variable_Impl>()->name();
}

void UtilityCost_Variable::setName(const std::string& str)
{
  getImpl<detail::UtilityCost_Variable_Impl>()->setName(str);
}

OptionalString UtilityCost_Variable::tariffName() const
{
  return getImpl<detail::UtilityCost_Variable_Impl>()->tariffName();
}

void UtilityCost_Variable::setTariffName(const std::string& str)
{
  getImpl<detail::UtilityCost_Variable_Impl>()->setTariffName(str);
}

OptionalString UtilityCost_Variable::variableType() const
{
  return getImpl<detail::UtilityCost_Variable_Impl>()->variableType();
}

void UtilityCost_Variable::setVariableType(const std::string& str)
{
  getImpl<detail::UtilityCost_Variable_Impl>()->setVariableType(str);
}

IddObjectType UtilityCost_Variable::iddObjectType()
{
  IddObjectType result(IddObjectType::OS_UtilityCost_Variable);
  return result;
}

} // model
} // openstudio


text:
// ====================================================================
// This file is part of FlexibleSUSY.
//
// FlexibleSUSY is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// FlexibleSUSY 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
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with FlexibleSUSY.  If not, see
// <http://www.gnu.org/licenses/>.
// ====================================================================

// File generated at Sat 27 Aug 2016 12:48:00

#ifndef MSSMatMGUT_INPUT_PARAMETERS_H
#define MSSMatMGUT_INPUT_PARAMETERS_H

#include <complex>
#include <Eigen/Core>

namespace flexiblesusy {

struct MSSMatMGUT_input_parameters {
   double TanBeta;
   int SignMu;
   double mHd2IN;
   double mHu2IN;
   Eigen::Matrix<double,3,3> Aeij;
   Eigen::Matrix<double,3,3> Adij;
   Eigen::Matrix<double,3,3> Auij;
   Eigen::Matrix<double,3,3> mq2Input;
   Eigen::Matrix<double,3,3> ml2Input;
   Eigen::Matrix<double,3,3> md2Input;
   Eigen::Matrix<double,3,3> mu2Input;
   Eigen::Matrix<double,3,3> me2Input;
   double MassBInput;
   double MassWBInput;
   double MassGInput;

   MSSMatMGUT_input_parameters()
      : TanBeta(0), SignMu(1), mHd2IN(0), mHu2IN(0), Aeij(Eigen::Matrix<double,3,3
   >::Zero()), Adij(Eigen::Matrix<double,3,3>::Zero()), Auij(Eigen::Matrix<
   double,3,3>::Zero()), mq2Input(Eigen::Matrix<double,3,3>::Zero()), ml2Input(
   Eigen::Matrix<double,3,3>::Zero()), md2Input(Eigen::Matrix<double,3,3>::Zero
   ()), mu2Input(Eigen::Matrix<double,3,3>::Zero()), me2Input(Eigen::Matrix<
   double,3,3>::Zero()), MassBInput(0), MassWBInput(0), MassGInput(0)

   {}

   Eigen::ArrayXd get() const;
   void set(const Eigen::ArrayXd&);
};

std::ostream& operator<<(std::ostream&, const MSSMatMGUT_input_parameters&);

} // namespace flexiblesusy

#endif

ext: hpp


text:
//=======================================================================
// Copyright (c)
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
/**
 * @file 2_local_search_test.cpp
 * @brief
 * @author Piotr Wygocki
 * @version 1.0
 * @date 2013-09-20
 */
#include "test_utils/sample_graph.hpp"
#include "test_utils/logger.hpp"
#include "test_utils/2_local_search_logger.hpp"

#include "paal/local_search/2_local_search/2_local_search.hpp"
#include "paal/data_structures/cycle/simple_cycle.hpp"

#include <boost/test/unit_test.hpp>

#include <vector>
#include <string>

using std::string;
using std::vector;
using namespace paal::local_search;
using namespace paal;

BOOST_AUTO_TEST_CASE(two_local_search_test) {
    //! [Two Local Search Example]
    // sample data
    typedef sample_graphs_metrics SGM;
    auto gm = SGM::get_graph_metric_small();
    const int size = gm.size();
    std::vector<int> v(size);
    std::iota(v.begin(), v.end(), 0);

    // create random solution
    std::random_shuffle(v.begin(), v.end());
    typedef data_structures::simple_cycle<int> Cycle;
    Cycle cycle(v.begin(), v.end());

    // creating local search components
    auto lsc = get_default_two_local_components(gm);

    // printing
    LOGLN("Length \t" << get_cycle_length(gm, cycle));

    // setting logger
    auto logger = utils::make_two_ls_logger(gm, 100);

    // search
    two_local_search(cycle, local_search::first_improving_strategy{}, logger,
                     utils::always_false(), lsc);
    //! [Two Local Search Example]
}

max_stars_repo_name: Kommeren/AA

max_issues_repo_name: Kommeren/AA

max_forks_repo_name: Kommeren/AA


text:
///////////////////////////////////////////////////////////////////////////////
// Copyright Christopher Kormanyos 2014.
// Copyright John Maddock 2014.
// Copyright Paul Bristow 2014.
// Distributed under the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
//

// <boost/cstdfloat.hpp> implements floating-point typedefs having
// specified widths, as described in N3626 (proposed for C++14).
// See: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3626.pdf

#ifndef BOOST_MATH_CSTDFLOAT_2014_01_09_HPP_
  #define BOOST_MATH_CSTDFLOAT_2014_01_09_HPP_

  // Include the floating-point type definitions.
  #include <boost/math/cstdfloat/cstdfloat_types.hpp>

  // Support a specialization of std::numeric_limits<> for the wrapped quadmath library (if available).
  #if !defined(BOOST_CSTDFLOAT_NO_LIBQUADMATH_LIMITS)
    #include <boost/math/cstdfloat/cstdfloat_limits.hpp>
  #endif

  // Support <cmath> functions for the wrapped quadmath library (if available).
  #if !defined(BOOST_CSTDFLOAT_NO_LIBQUADMATH_CMATH)
    #include <boost/math/cstdfloat/cstdfloat_cmath.hpp>
  #endif

  // Support I/O stream operations for the wrapped quadmath library (if available).
  #if !defined(BOOST_CSTDFLOAT_NO_LIBQUADMATH_IOSTREAM)
    #if defined(BOOST_CSTDFLOAT_NO_LIBQUADMATH_CMATH)
    #error You can not use <boost/math/cstdfloat/cstdfloat_iostream.hpp> with BOOST_CSTDFLOAT_NO_LIBQUADMATH_CMATH defined.
    #endif
    #include <boost/math/cstdfloat/cstdfloat_iostream.hpp>
  #endif

  // Support a specialization of std::complex<> for the wrapped quadmath library (if available).
  #if !defined(BOOST_CSTDFLOAT_NO_LIBQUADMATH_COMPLEX)
    #if defined(BOOST_CSTDFLOAT_NO_LIBQUADMATH_LIMITS)
    #error You can not use <boost/math/cstdfloat/cstdfloat_complex.hpp> with BOOST_CSTDFLOAT_NO_LIBQUADMATH_LIMITS defined.
    #endif
    #if defined(BOOST_CSTDFLOAT_NO_LIBQUADMATH_CMATH)
    #error You can not use <boost/math/cstdfloat/cstdfloat_complex.hpp> with BOOST_CSTDFLOAT_NO_LIBQUADMATH_CMATH defined.
    #endif
    #if defined(BOOST_CSTDFLOAT_NO_LIBQUADMATH_IOSTREAM)
    #error You can not use <boost/math/cstdfloat/cstdfloat_complex.hpp> with BOOST_CSTDFLOAT_NO_LIBQUADMATH_IOSTREAM defined.
    #endif
    #include <boost/math/cstdfloat/cstdfloat_complex.hpp>
  #endif

  // Undefine BOOST_NO_FLOAT128_T because this constant is not meant for public use.
  #if defined(BOOST_CSTDFLOAT_HAS_INTERNAL_FLOAT128_T)
  #undef BOOST_CSTDFLOAT_HAS_INTERNAL_FLOAT128_T
  #endif

#endif // BOOST_MATH_CSTDFLOAT_2014_01_09_HPP_


text:
#include <vector>
#include <boost/type_traits/integral_constant.hpp>

template <class T>
struct is_stdvector: boost::false_type {};

template <class T, class Allocator>
struct is_stdvector<std::vector<T, Allocator> >: boost::true_type {};

#include <boost/static_assert.hpp>
int main () {
    BOOST_STATIC_ASSERT(is_stdvector<std::vector<char> >::value);
    BOOST_STATIC_ASSERT(!is_stdvector<char>::value);
    BOOST_STATIC_ASSERT(!is_stdvector<int>::value);
}

max_stars_repo_name: apolukhin/boost-cookbook

max_issues_repo_name: apolukhin/boost-cookbook

max_forks_repo_name: apolukhin/boost-cookbook


text:
// (C) Copyright Stephan Dollberg 2012-2013. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BAM_PARALLEL_FIND_HPP
#define BAM_PARALLEL_FIND_HPP

#include "detail/work_range.hpp"
#include "detail/parallel_utility.hpp"
#include <boost/range/algorithm.hpp>
#include <tuple>
#include <atomic>

namespace bam {
    namespace detail {
        // looks for a non-end iterator and then returns it
        template<typename Container, typename Iter>
        Iter join_iter(Container& c, Iter default_iter) {
            for(auto&& task : c) {
                auto iter = task.get();
                if(iter != default_iter) {
                    return iter;
                }
            }

            return default_iter;
        }
    }

    /**
     * @brief searches val in range [begin, end)
     * @return returns an iterator to one occurange of val, if the value was not found returns end
     */
    template<typename Iter, typename T>
    Iter parallel_find(Iter begin, Iter end, const T& val, int grainsize = 0) {
        // get params work_piece_per_thread and grainsize
        auto work_piece_per_thread = 0;
        std::tie(grainsize, work_piece_per_thread) = detail::get_scheduler_params(end - begin, grainsize);

        if(work_piece_per_thread == 0) {
            return end;
        }

        // build work
        std::atomic<bool> done(false);
        auto work = detail::make_work(begin, end, work_piece_per_thread, grainsize);

        // helper function which the threads will run
        auto work_helper = [&] (detail::work_range<Iter>& work_rng) {
            std::pair<Iter, Iter> work_chunk;
            while(!done && work_rng.try_fetch_work(work_chunk, work)) {
                auto found_iter = boost::find(work_chunk, val);
                if(found_iter != work_chunk.second) {
                    done = true;
                    return found_iter;
                }
            }

            return end;
        };

        // spawn tasks
        auto tasks = detail::spawn_tasks(work, work_helper);

        // get tasks & rethrow
        return detail::join_iter(tasks, end);
    }

    /**
     * @brief searches for val in rng
     * @return returns an iterator to one occurance of the searched value, if value was not found returns an end iterator of rng
     */
    template<typename Range, typename T>
    auto parallel_find(Range&& rng, const T& val, int grainsize = 0) -> decltype(boost::begin(rng)) {
        return parallel_find(boost::begin(rng), boost::end(rng), val, grainsize);
    }
}

#endif // BAM_PARALLEL_FIND_HPP

max_stars_repo_name: StephanDollberg/BAM

max_issues_repo_name: StephanDollberg/BAM

max_forks_repo_name: StephanDollberg/BAM


text:
//#ifndef _WEBSOCKETPP_CPP11_STL_
//    #define _WEBSOCKETPP_CPP11_STL_
//#endif

#include <random>
#include <boost/timer/timer.hpp>

#include <websocketpp/config/core.hpp>

//#include <websocketpp/security/none.hpp>

//#include <websocketpp/concurrency/none.hpp>
//#include <websocketpp/concurrency/stl.hpp>

//#include <websocketpp/transport/iostream.hpp>
#include <websocketpp/server.hpp>

#include <iostream>
#include <sstream>

//typedef websocketpp::concurrency::stl concurrency;
//typedef websocketpp::transport::iostream<concurrency> transport;
//typedef websocketpp::server<concurrency,transport> server;
typedef websocketpp::server<websocketpp::config::core> server;

/*class handler : public server::handler {
    bool validate(connection_ptr con) {
        std::cout << "handler validate" << std::endl;
        if (con->get_origin() != "http://www.example.com") {
            con->set_status(websocketpp::http::status_code::FORBIDDEN);
            return false;
        }
        return true;
    }

    void http(connection_ptr con) {
        std::cout << "handler http" << std::endl;
    }

    void on_load(connection_ptr con, ptr old_handler) {
        std::cout << "handler on_load" << std::endl;
    }
    void on_unload(connection_ptr con, ptr new_handler) {
        std::cout << "handler on_unload" << std::endl;
    }

    void on_open(connection_ptr con) {
        std::cout << "handler on_open" << std::endl;
    }
    void on_fail(connection_ptr con) {
        std::cout << "handler on_fail" << std::endl;
    }

    void on_message(connection_ptr con, message_ptr msg) {
        std::cout << "handler on_message" << std::endl;

    }

    void on_close(connection_ptr con) {
        std::cout << "handler on_close" << std::endl;
    }
};*/

int main() {
    typedef websocketpp::message_buffer::message<websocketpp::message_buffer::alloc::con_msg_manager>
        message_type;
    typedef websocketpp::message_buffer::alloc::con_msg_manager<message_type>
        con_msg_man_type;

    con_msg_man_type::ptr manager = websocketpp::lib::make_shared<con_msg_man_type>();

    size_t foo = 1024;

    message_type::ptr input = manager->get_message(websocketpp::frame::opcode::TEXT,foo);
    message_type::ptr output = manager->get_message(websocketpp::frame::opcode::TEXT,foo);
    websocketpp::frame::masking_key_type key;

    std::random_device dev;

    key.i = 0x12345678;

    double m = 18094238402394.0824923;

    /*std::cout << "Some Math" << std::endl;
    {
        boost::timer::auto_cpu_timer t;

        for (int i = 0; i < foo; i++) {
            m /= 1.001;
        }

    }*/

    std::cout << m << std::endl;

    std::cout << "Random Gen" << std::endl;
    {
        boost::timer::auto_cpu_timer t;

        input->get_raw_payload().replace(0,foo,foo,'\0');
        output->get_raw_payload().replace(0,foo,foo,'\0');
    }

    std::cout << "Out of place accelerated" << std::endl;
    {
        boost::timer::auto_cpu_timer t;

        websocketpp::frame::word_mask_exact(reinterpret_cast<uint8_t*>(const_cast<char*>(input->get_raw_payload().data())), reinterpret_cast<uint8_t*>(const_cast<char*>(output->get_raw_payload().data())), foo, key);
    }

    std::cout << websocketpp::utility::to_hex(input->get_payload().c_str(),20) << std::endl;
    std::cout << websocketpp::utility::to_hex(output->get_payload().c_str(),20) << std::endl;

    input->get_raw_payload().replace(0,foo,foo,'\0');
    output->get_raw_payload().replace(0,foo,foo,'\0');

    std::cout << "In place accelerated" << std::endl;
    {
        boost::timer::auto_cpu_timer t;

        websocketpp::frame::word_mask_exact(reinterpret_cast<uint8_t*>(const_cast<char*>(input->get_raw_payload().data())), reinterpret_cast<uint8_t*>(const_cast<char*>(input->get_raw_payload().data())), foo, key);
    }

    std::cout << websocketpp::utility::to_hex(input->get_payload().c_str(),20) << std::endl;
    std::cout << websocketpp::utility::to_hex(output->get_payload().c_str(),20) << std::endl;

    input->get_raw_payload().replace(0,foo,foo,'\0');
    output->get_raw_payload().replace(0,foo,foo,'\0');
    std::cout << "Out of place byte by byte" << std::endl;
    {
        boost::timer::auto_cpu_timer t;

        websocketpp::frame::byte_mask(input->get_raw_payload().begin(), input->get_raw_payload().end(), output->get_raw_payload().begin(), key);
    }

    std::cout << websocketpp::utility::to_hex(input->get_payload().c_str(),20) << std::endl;
    std::cout << websocketpp::utility::to_hex(output->get_payload().c_str(),20) << std::endl;

    input->get_raw_payload().replace(0,foo,foo,'\0');
    output->get_raw_payload().replace(0,foo,foo,'\0');
    std::cout << "In place byte by byte" << std::endl;
    {
        boost::timer::auto_cpu_timer t;

        websocketpp::frame::byte_mask(input->get_raw_payload().begin(), input->get_raw_payload().end(), input->get_raw_payload().begin(), key);
    }

    std::cout << websocketpp::utility::to_hex(input->get_payload().c_str(),20) << std::endl;
    std::cout << websocketpp::utility::to_hex(output->get_payload().c_str(),20) << std::endl;

    input->get_raw_payload().replace(0,foo,foo,'a');
    output->get_raw_payload().replace(0,foo,foo,'b');
    std::cout << "Copy" << std::endl;
    {
        boost::timer::auto_cpu_timer t;

        std::copy(input->get_raw_payload().begin(), input->get_raw_payload().end(), output->get_raw_payload().begin());
    }

    std::cout << websocketpp::utility::to_hex(input->get_payload().c_str(),20) << std::endl;
    std::cout << websocketpp::utility::to_hex(output->get_payload().c_str(),20) << std::endl;

    /*server::handler::ptr h(new handler());

    server test_server(h);
    server::connection_ptr con;

    std::stringstream output;

    test_server.register_ostream(&output);

    con = test_server.get_connection();

    con->start();

    //foo.handle_accept(con,true);

    std::stringstream input;
    input << "GET / HTTP/1.1\r\nHost: www.example.com\r\nConnection: upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nOrigin: http://www.example.com\r\n\r\n";
    //input << "GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n";
    input >> *con;

    std::stringstream input2;
    input2 << "messageabc2";
    input2 >> *con;

    std::stringstream input3;
    input3 << "messageabc3";
    input3 >> *con;

    std::stringstream input4;
    input4 << "close";
    input4 >> *con;

    std::cout << "connection output:" << std::endl;
    std::cout << output.str() << std::endl;*/
}

max_stars_repo_name: EOTSIO/EOT

max_issues_repo_name: EOTSIO/EOT

max_forks_repo_name: EOTSIO/EOT


text:
#include "StdAfx.h"
#include "destination_parser.h"

#include <boost/test/unit_test.hpp>

#ifdef UNIT_TEST

BOOST_AUTO_TEST_SUITE( TestWebBrowser )

	BOOST_AUTO_TEST_CASE( no_colon )
	{
		destination_parser parser ;
		wstring destination = L"foo" ;
		LPMSG expected = NULL ;
		BOOST_CHECK_EQUAL(expected, parser.parse(destination)) ;
	}

	BOOST_AUTO_TEST_CASE( category_not_number )
	{
		destination_parser parser ;
		wstring destination = L"foo:bar" ;
		LPMSG expected = NULL ;
		BOOST_CHECK_EQUAL(expected, parser.parse(destination)) ;
	}

	BOOST_AUTO_TEST_CASE( sub_category_not_number )
	{
		destination_parser parser ;
		wstring destination = L"145:bar" ;
		LPMSG expected = NULL ;
		BOOST_CHECK_EQUAL(expected, parser.parse(destination)) ;
	}

	BOOST_AUTO_TEST_CASE( parse_155_103 )
	{
		destination_parser parser ;
		wstring destination = L"155:103" ;
		LPMSG msg = parser.parse(destination) ;
		BOOST_CHECK_EQUAL(155u, msg->wParam) ;
		BOOST_CHECK_EQUAL(103, msg->lParam) ;
	}

BOOST_AUTO_TEST_SUITE_END()

#endif

max_stars_repo_name: ultimatezen/felix

max_issues_repo_name: ultimatezen/felix

max_forks_repo_name: ultimatezen/felix


text:
//  Boost string_algo library find_format_store.hpp header file  ---------------------------//

//  Copyright Pavol Droba 2002-2003.
//
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

//  See http://www.boost.org/ for updates, documentation, and revision history.

#ifndef BOOST_STRING_FIND_FORMAT_STORE_DETAIL_HPP
#define BOOST_STRING_FIND_FORMAT_STORE_DETAIL_HPP

#include <boost/algorithm/string/config.hpp>
#include <boost/range/iterator_range.hpp>

namespace boost {
    namespace algorithm {
        namespace detail {

//  temporary format and find result storage --------------------------------//

#if BOOST_WORKAROUND(BOOST_MSVC, >= 1400)
#pragma warning(push)
#pragma warning(disable:4512) //assignment operator could not be generated
#endif
            template<
                typename ForwardIteratorT,
                typename FormatterT,
                typename FormatResultT >
            class find_format_store :
                public iterator_range<ForwardIteratorT>
            {
            public:
                // typedefs
                typedef iterator_range<ForwardIteratorT> base_type;
                typedef FormatterT  formatter_type;
                typedef FormatResultT format_result_type;

            public:
                // Construction
                find_format_store(
                        const base_type& FindResult,
                        const format_result_type& FormatResult,
                        const formatter_type& Formatter ) :
                    base_type(FindResult),
                    m_FormatResult(FormatResult),
                    m_Formatter(Formatter) {}

                // Assignment
                template< typename FindResultT >
                find_format_store& operator=( FindResultT FindResult )
                {
                    iterator_range<ForwardIteratorT>::operator=(FindResult);
                    if( !this->empty() ) {
                    m_FormatResult=m_Formatter(FindResult);
                    }

                    return *this;
                }

                // Retrieve format result
                const format_result_type& format_result()
                {
                    return m_FormatResult;
                }

            private:
                format_result_type m_FormatResult;
                const formatter_type& m_Formatter;
            };

            template<typename InputT, typename FindResultT>
            bool check_find_result(InputT& Input, FindResultT& FindResult)
            {
                typedef BOOST_STRING_TYPENAME
                    range_const_iterator<InputT>::type input_iterator_type;
                iterator_range<input_iterator_type> ResultRange(FindResult);
                return !ResultRange.empty();
            }

#if BOOST_WORKAROUND(BOOST_MSVC, >= 1400)
#pragma warning(pop)
#endif
        } // namespace detail
    } // namespace algorithm
} // namespace boost

#endif  // BOOST_STRING_FIND_FORMAT_STORE_DETAIL_HPP

max_issues_repo_name: benkaraban/anima-games-engine

max_forks_repo_name: benkaraban/anima-games-engine


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

#include <boost/test/unit_test.hpp>
#include <fstream>
#include <cstdio>
#include <cstring>

#include "kaa/security/KeyUtils.hpp"

#ifndef RESOURCE_DIR
#error "No path to resources defined!"
#endif

namespace kaa {

struct KeyUtilsFixture
{
    KeyUtilsFixture()
        :newPublicKeyPath{RESOURCE_DIR"/key.new_public"}
        ,newPrivateKeyPath{RESOURCE_DIR"/key.new_private"}
        ,keyUtils{}
        ,generatedKeyPair{keyUtils.generateKeyPair(keyLength)}
    {

    }

    ~KeyUtilsFixture()
    {
        std::remove(newPublicKeyPath.c_str());
        std::remove(newPrivateKeyPath.c_str());
    }

    void saveKeyPairToFiles()
    {
        KeyUtils::saveKeyPair(generatedKeyPair, newPublicKeyPath, newPrivateKeyPath);
    }

    KeyPair loadKeyPairsFromFiles()
    {
        return KeyUtils::loadKeyPair(newPublicKeyPath, newPrivateKeyPath);
    }

    static constexpr size_t keyLength = 2048;

    const std::string newPublicKeyPath;
    const std::string newPrivateKeyPath;

    KeyUtils keyUtils;
    KeyPair  generatedKeyPair;
};

BOOST_AUTO_TEST_SUITE(KeyUtilsTestSuite)

BOOST_FIXTURE_TEST_CASE(GeneratedKeysAreValid, KeyUtilsFixture)
{
    BOOST_CHECK(keyUtils.checkKeyPair(generatedKeyPair));
}

BOOST_FIXTURE_TEST_CASE(CorruptedPrivateKeyIsNotValid, KeyUtilsFixture)
{
    saveKeyPairToFiles();

    std::fstream priv(newPrivateKeyPath.c_str(),
                      std::ios::out | std::ios::in);

    // Corrupt private key somewhere in the middle of the file
    priv.seekp(50);
    priv << "TheAnswerToTheUltimateQuestionOfLifeTheUniverseAndEverythingIs42\n";
    priv.close();

    auto loadedKeyPair = loadKeyPairsFromFiles();
    BOOST_CHECK(!keyUtils.checkKeyPair(loadedKeyPair));
}

BOOST_FIXTURE_TEST_CASE(CorruptedPublicKeyIsNotValid, KeyUtilsFixture)
{
    saveKeyPairToFiles();

    std::fstream pub(newPublicKeyPath.c_str(),
                     std::ios::out | std::ios::in);

    // Corrupt public key somewhere in the middle of the file
    pub.seekp(20);
    pub << 42;
    pub.close();

    auto loadedKeyPair = loadKeyPairsFromFiles();
    BOOST_CHECK(!keyUtils.checkKeyPair(loadedKeyPair));
}

BOOST_FIXTURE_TEST_CASE(SaveLoadKeyPairTest, KeyUtilsFixture)
{
    saveKeyPairToFiles();
    auto loadedKeyPair = loadKeyPairsFromFiles();

    BOOST_CHECK_MESSAGE(generatedKeyPair.getPublicKey() == loadedKeyPair.getPublicKey()
                                    , "Loaded and saved public key don't match");
    BOOST_CHECK_MESSAGE(generatedKeyPair.getPrivateKey() == loadedKeyPair.getPrivateKey()
                                    , "Loaded and saved private key don't match");

    BOOST_CHECK(keyUtils.checkKeyPair(loadedKeyPair));
}

BOOST_AUTO_TEST_SUITE_END()

}


text: #include <boost/geometry/multi/geometries/concepts/multi_polygon_concept.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/*
 * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The OpenAirInterface Software Alliance licenses this file to You under
 * the OAI Public License, Version 1.1  (the "License"); you may not use this
 * file except in compliance with the License. You may obtain a copy of the
 * License at
 *
 *      http://www.openairinterface.org/?page_id=698
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *-------------------------------------------------------------------------------
 * For more information about the OpenAirInterface (OAI) Software Alliance:
 *      contact@openairinterface.org
 */

/*! \file nrf_config.cpp
 \brief
 \author  Lionel GAUTHIER, Tien-Thinh NGUYEN
 \company Eurecom
 \date 2019
 \email: lionel.gauthier@eurecom.fr, tien-thinh.nguyen@eurecom.fr
 */

#include "nrf_config.hpp"

#include <cstdlib>
#include <iomanip>
#include <iostream>
#include "string.hpp"

// C includes
#include <arpa/inet.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>

#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>

#include "common_defs.h"
#include "if.hpp"
#include "logger.hpp"
#include "nrf_app.hpp"

using namespace std;
using namespace libconfig;
using namespace oai::nrf::app;

extern nrf_config nrf_cfg;

//------------------------------------------------------------------------------
int nrf_config::load_interface(const Setting& if_cfg, interface_cfg_t& cfg) {
  if_cfg.lookupValue(NRF_CONFIG_STRING_INTERFACE_NAME, cfg.if_name);
  util::trim(cfg.if_name);
  if (not boost::iequals(cfg.if_name, "none")) {
    std::string address = {};
    if_cfg.lookupValue(NRF_CONFIG_STRING_IPV4_ADDRESS, address);
    util::trim(address);
    if (boost::iequals(address, "read")) {
      if (get_inet_addr_infos_from_iface(
              cfg.if_name, cfg.addr4, cfg.network4, cfg.mtu)) {
        Logger::nrf_app().error(
            "Could not read %s network interface configuration", cfg.if_name);
        return RETURNerror;
      }
    } else {
      std::vector<std::string> words;
      boost::split(
          words, address, boost::is_any_of("/"), boost::token_compress_on);
      if (words.size() != 2) {
        Logger::nrf_app().error(
            "Bad value " NRF_CONFIG_STRING_IPV4_ADDRESS " = %s in config file",
            address.c_str());
        return RETURNerror;
      }
      unsigned char buf_in_addr[sizeof(struct in6_addr)];
      if (inet_pton(AF_INET, util::trim(words.at(0)).c_str(), buf_in_addr) ==
          1) {
        memcpy(&cfg.addr4, buf_in_addr, sizeof(struct in_addr));
      } else {
        Logger::nrf_app().error(
            "In conversion: Bad value " NRF_CONFIG_STRING_IPV4_ADDRESS
            " = %s in config file",
            util::trim(words.at(0)).c_str());
        return RETURNerror;
      }
      cfg.network4.s_addr = htons(
          ntohs(cfg.addr4.s_addr) &
          0xFFFFFFFF << (32 - std::stoi(util::trim(words.at(1)))));
    }
    if_cfg.lookupValue(NRF_CONFIG_STRING_PORT, cfg.port);
  }
  return RETURNok;
}

//------------------------------------------------------------------------------
int nrf_config::load(const string& config_file) {
  Config cfg;
  unsigned char buf_in6_addr[sizeof(struct in6_addr)];

  // Read the file. If there is an error, report it and exit.
  try {
    cfg.readFile(config_file.c_str());
  } catch (const FileIOException& fioex) {
    Logger::nrf_app().error(
        "I/O error while reading file %s - %s", config_file.c_str(),
        fioex.what());
    throw;
  } catch (const ParseException& pex) {
    Logger::nrf_app().error(
        "Parse error at %s:%d - %s", pex.getFile(), pex.getLine(),
        pex.getError());
    throw;
  }

  const Setting& root = cfg.getRoot();

  try {
    const Setting& nrf_cfg = root[NRF_CONFIG_STRING_NRF_CONFIG];
  } catch (const SettingNotFoundException& nfex) {
    Logger::nrf_app().error("%s : %s", nfex.what(), nfex.getPath());
    return RETURNerror;
  }

  const Setting& nrf_cfg = root[NRF_CONFIG_STRING_NRF_CONFIG];

  try {
    nrf_cfg.lookupValue(NRF_CONFIG_STRING_INSTANCE, instance);
  } catch (const SettingNotFoundException& nfex) {
    Logger::nrf_app().info(
        "%s : %s, using defaults", nfex.what(), nfex.getPath());
  }

  try {
    nrf_cfg.lookupValue(NRF_CONFIG_STRING_PID_DIRECTORY, pid_dir);
  } catch (const SettingNotFoundException& nfex) {
    Logger::nrf_app().info(
        "%s : %s, using defaults", nfex.what(), nfex.getPath());
  }

  try {
    const Setting& sbi_cfg = nrf_cfg[NRF_CONFIG_STRING_INTERFACE_SBI];
    load_interface(sbi_cfg, sbi);

    // HTTP2 port
    if (!(sbi_cfg.lookupValue(
            NRF_CONFIG_STRING_SBI_HTTP2_PORT, sbi_http2_port))) {
      Logger::nrf_app().error(NRF_CONFIG_STRING_SBI_HTTP2_PORT "failed");
      throw(NRF_CONFIG_STRING_SBI_HTTP2_PORT "failed");
    }

    // SBI API VERSION
    if (!(sbi_cfg.lookupValue(
            NRF_CONFIG_STRING_API_VERSION, sbi_api_version))) {
      Logger::nrf_app().error(NRF_CONFIG_STRING_API_VERSION "failed");
      throw(NRF_CONFIG_STRING_API_VERSION "failed");
    }

  } catch (const SettingNotFoundException& nfex) {
    Logger::nrf_app().error("%s : %s", nfex.what(), nfex.getPath());
    return RETURNerror;
  }

  return true;
}

//------------------------------------------------------------------------------
void nrf_config::display() {
  Logger::nrf_app().info(
      "==== OAI-CN5G %s v%s ====", PACKAGE_NAME, PACKAGE_VERSION);
  Logger::nrf_app().info("Configuration NRF:");
  Logger::nrf_app().info("- Instance ..............: %d\n", instance);
  Logger::nrf_app().info("- PID dir ...............: %s\n", pid_dir.c_str());

  Logger::nrf_app().info("- SBI Interface:");
  Logger::nrf_app().info("    Interface name ......: %s", sbi.if_name.c_str());
  Logger::nrf_app().info("    IPv4 Addr ...........: %s", inet_ntoa(sbi.addr4));
  Logger::nrf_app().info("    Port ................: %d", sbi.port);
  Logger::nrf_app().info("    HTTP2 port ..........: %d", sbi_http2_port);
  Logger::nrf_app().info(
      "    API version..........: %s", sbi_api_version.c_str());
}

//------------------------------------------------------------------------------
nrf_config::~nrf_config() {}


text:
/*
Copyright 2011, 2012, 2014 Rogier van Dalen.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#define BOOST_TEST_MODULE test_rime_variant
#include "utility/test/boost_unit_test.hpp"

#include <type_traits>

#include <boost/mpl/assert.hpp>

#include "utility/test/tracked.hpp"
#include <string>

// GCC rightfully complains about comparisons between signed and unsigned
// integers when testing binary operators.
// However, all we require here is for the behaviour to be the same between
// the variant and non-variant versions.
// (This includes warnings, but that is hard to test for.)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wsign-compare"

#include "rime/variant.hpp"

#include <iostream>
#include <array>

struct convertee {};
struct converted {
    converted() {}
    converted (convertee) {}
};

BOOST_MPL_ASSERT ((std::is_convertible <convertee &&, converted>));

int const && get_int_const() {
    static int i = 5;
    return static_cast <int const &&> (i);
}

using std::is_same;

typedef rime::variant <
    /* 0 */ int, /* 1 */ float, /* 2 */ int &,
    /* 3 */ int const, /* 4 */ int const &,
    /* 5 */ std::string, /* 6 */ void *, /* 7 */ char *,
    /* 8 */ converted,
    /* 9 */ void
> variant;

typedef rime::variant <
    /* 0 */ int, /* 1 */ float, /* 2 */ int &,
    /* 3 */ int const, /* 4 */ int const &
> other_variant;

template <typename T> variant make_variant (T && o)
{ return variant (std::forward <T> (o)); }

template <typename T> variant const make_const_variant (T && o)
{ return variant (std::forward <T> (o)); }

template <typename T> other_variant make_other_variant (T && o)
{ return other_variant (std::forward <T> (o)); }

template <typename T> other_variant const make_const_other_variant (T && o)
{ return other_variant (std::forward <T> (o)); }

// Make void versions
variant make_variant() { return variant(); }
variant const make_const_variant() { return variant(); }

BOOST_AUTO_TEST_SUITE(test_rime_variant)

BOOST_AUTO_TEST_CASE (test_rime_variant_get_types) {
    // return types for "get"
    {
        variant v (6);
        BOOST_MPL_ASSERT ((is_same <int &,
            decltype (rime::get <int> (v))>));
        BOOST_MPL_ASSERT ((is_same <float &,
            decltype (rime::get <float> (v))>));
        BOOST_MPL_ASSERT ((is_same <int &,
            decltype (rime::get <int &> (v))>));
        BOOST_MPL_ASSERT ((is_same <int const &,
            decltype (rime::get <int const> (v))>));
        BOOST_MPL_ASSERT ((is_same <int const &,
            decltype (rime::get <int const &> (v))>));
        BOOST_MPL_ASSERT ((is_same <std::string &,
            decltype (rime::get <std::string> (v))>));
        BOOST_MPL_ASSERT ((is_same <void * &,
            decltype (rime::get <void *> (v))>));
        BOOST_MPL_ASSERT ((is_same <converted &,
            decltype (rime::get <converted> (v))>));
        BOOST_MPL_ASSERT ((is_same <void,
            decltype (rime::get <void> (v))>));

        BOOST_MPL_ASSERT ((is_same <int &&,
            decltype (rime::get <int> (make_variant (6)))>));
        BOOST_MPL_ASSERT ((is_same <float &&,
            decltype (rime::get <float> (make_variant (6)))>));
        BOOST_MPL_ASSERT ((is_same <int &,
            decltype (rime::get <int &> (make_variant (6)))>));
        BOOST_MPL_ASSERT ((is_same <int const &&,
            decltype (rime::get <int const> (make_variant (6)))>));
        BOOST_MPL_ASSERT ((is_same <int const &,
            decltype (rime::get <int const &> (make_variant (6)))>));
        BOOST_MPL_ASSERT ((is_same <std::string &&,
            decltype (rime::get <std::string> (make_variant (6)))>));
        BOOST_MPL_ASSERT ((is_same <void * &&,
            decltype (rime::get <void *> (make_variant (6)))>));
        BOOST_MPL_ASSERT ((is_same <converted &&,
            decltype (rime::get <converted> (make_variant (6)))>));
        BOOST_MPL_ASSERT ((is_same <void,
            decltype (rime::get <void> (make_variant (6)))>));

        BOOST_MPL_ASSERT ((is_same <int *,
            decltype (rime::get <int> (&v))>));
        BOOST_MPL_ASSERT ((is_same <float *,
            decltype (rime::get <float> (&v))>));
/*        BOOST_MPL_ASSERT ((is_same <fails,
            decltype (rime::get <int &> (&v))>));*/
        BOOST_MPL_ASSERT ((is_same <int const *,
            decltype (rime::get <int const> (&v))>));
/*        BOOST_MPL_ASSERT ((is_same <fails,
            decltype (rime::get <int const &> (&v))>));*/
        BOOST_MPL_ASSERT ((is_same <std::string *,
            decltype (rime::get <std::string> (&v))>));
        BOOST_MPL_ASSERT ((is_same <void **,
            decltype (rime::get <void *> (&v))>));
        BOOST_MPL_ASSERT ((is_same <converted *,
            decltype (rime::get <converted> (&v))>));
        BOOST_MPL_ASSERT ((is_same <void *,
            decltype (rime::get <void> (&v))>));

        variant const vc (6);
        BOOST_MPL_ASSERT ((is_same <int const &,
            decltype (rime::get <int> (vc))>));
        BOOST_MPL_ASSERT ((is_same <float const &,
            decltype (rime::get <float> (vc))>));
        BOOST_MPL_ASSERT ((is_same <int &,
            decltype (rime::get <int &> (vc))>));
        BOOST_MPL_ASSERT ((is_same <int const &,
            decltype (rime::get <int const> (vc))>));
        BOOST_MPL_ASSERT ((is_same <int const &,
            decltype (rime::get <int const &> (vc))>));
        BOOST_MPL_ASSERT ((is_same <std::string const &,
            decltype (rime::get <std::string> (vc))>));
        BOOST_MPL_ASSERT ((is_same <void * const &,
            decltype (rime::get <void *> (vc))>));
        BOOST_MPL_ASSERT ((is_same <converted const &,
            decltype (rime::get <converted> (vc))>));
        BOOST_MPL_ASSERT ((is_same <void,
            decltype (rime::get <void> (vc))>));

        BOOST_MPL_ASSERT ((is_same <int const &&,
            decltype (rime::get <int> (make_const_variant (6)))>));
        BOOST_MPL_ASSERT ((is_same <float const &&,
            decltype (rime::get <float> (make_const_variant (6)))>));
        BOOST_MPL_ASSERT ((is_same <int &,
            decltype (rime::get <int &> (make_const_variant (6)))>));
        BOOST_MPL_ASSERT ((is_same <int const &&,
            decltype (rime::get <int const> (make_const_variant (6)))>));
        BOOST_MPL_ASSERT ((is_same <int const &,
            decltype (rime::get <int const &> (make_const_variant (6)))>));
        BOOST_MPL_ASSERT ((is_same <std::string const &&,
            decltype (rime::get <std::string> (make_const_variant (6)))>));
        BOOST_MPL_ASSERT ((is_same <void * const &&,
            decltype (rime::get <void *> (make_const_variant (6)))>));
        BOOST_MPL_ASSERT ((is_same <converted const &&,
            decltype (rime::get <converted> (make_const_variant (6)))>));
        BOOST_MPL_ASSERT ((is_same <void,
            decltype (rime::get <void> (make_const_variant (6)))>));

        BOOST_MPL_ASSERT ((is_same <int const *,
            decltype (rime::get <int> (&vc))>));
        BOOST_MPL_ASSERT ((is_same <float const *,
            decltype (rime::get <float> (&vc))>));
        /*BOOST_MPL_ASSERT ((is_same <fails,
            decltype (rime::get <int &> (&vc))>));*/
        BOOST_MPL_ASSERT ((is_same <int const *,
            decltype (rime::get <int const> (&vc))>));
        /*BOOST_MPL_ASSERT ((is_same <
            decltype (rime::get <int const &> (&vc))>));*/
        BOOST_MPL_ASSERT ((is_same <std::string const *,
            decltype (rime::get <std::string> (&vc))>));
        BOOST_MPL_ASSERT ((is_same <void * const *,
            decltype (rime::get <void *> (&vc))>));
        BOOST_MPL_ASSERT ((is_same <converted const *,
            decltype (rime::get <converted> (&vc))>));
        BOOST_MPL_ASSERT ((is_same <void const *,
            decltype (rime::get <void> (&vc))>));
    }

    // index_of
    static_assert (variant::index_of <int>::value == 0, "");
    static_assert (variant::index_of <float>::value == 1, "");
    static_assert (variant::index_of <int &>::value == 2, "");
    static_assert (variant::index_of <int const>::value == 3, "");
    static_assert (variant::index_of <int const &>::value == 4, "");
    static_assert (variant::index_of <std::string>::value == 5, "");
    static_assert (variant::index_of <void *>::value == 6, "");
    static_assert (variant::index_of <char *>::value == 7, "");
    static_assert (variant::index_of <converted>::value == 8, "");
    static_assert (variant::index_of <void>::value == 9, "");
}

BOOST_AUTO_TEST_CASE (test_rime_variant) {
    // int &&
    {
        variant v (6);
        variant const vc (6);
        BOOST_CHECK_EQUAL (v.which(), 0u);
        BOOST_CHECK_EQUAL (vc.which(), 0u);
        BOOST_CHECK (v.contains <int>());
        BOOST_CHECK (vc.contains <int>());
        BOOST_CHECK (!v.contains <float>());
        BOOST_CHECK (!vc.contains <int const>());

        BOOST_CHECK_EQUAL (rime::get_unsafe <int> (v), 6);
        BOOST_CHECK_EQUAL (rime::get <int> (v), 6);
        BOOST_CHECK_EQUAL (rime::get <int> (vc), 6);

        BOOST_CHECK_THROW (rime::get <int &> (v), rime::bad_get);
        // Check that bad_get derives from std::runtime_error
        BOOST_CHECK_THROW (rime::get <int &> (v), std::runtime_error);
        BOOST_CHECK_THROW (rime::get <int const> (vc), rime::bad_get);
        BOOST_CHECK_EQUAL (rime::get <int const> (&vc), (int *) 0);

        BOOST_CHECK_EQUAL (rime::get <int> (&v), &rime::get <int> (v));
        BOOST_CHECK_EQUAL (rime::get <int> (&vc), &rime::get <int> (vc));
        BOOST_CHECK_EQUAL (*rime::get <int> (&v), 6);
        BOOST_CHECK_EQUAL (*rime::get <int> (&vc), 6);

        // Assignment
        rime::get_unsafe <int> (v) = 5;
        BOOST_CHECK_EQUAL (rime::get <int> (v), 5);
        rime::get <int> (v) = 4;
        BOOST_CHECK_EQUAL (*rime::get <int> (&v), 4);
        *rime::get <int> (&v) = 3;
        BOOST_CHECK_EQUAL (rime::get_unsafe <int> (v), 3);

        BOOST_CHECK_EQUAL (rime::get_unsafe <int> (variant (6)), 6);
    }
    {
        rime::variant <float, const int> v (6);
        BOOST_CHECK_EQUAL (v.which(), 1u);
        BOOST_CHECK (v.contains <const int>());
    }
    {
        rime::variant <float, const int &> v (6);
        // Can't be converted into const int &
        BOOST_CHECK_EQUAL (v.which(), 0u);
        BOOST_CHECK (v.contains <float>());
    }

    // int const
    {
        variant v (get_int_const());
        variant const vc (get_int_const());
        BOOST_CHECK_EQUAL (v.which(), 3u);
        BOOST_CHECK_EQUAL (vc.which(), 3u);
        BOOST_CHECK (!v.contains <int>());
        BOOST_CHECK (v.contains <int const>());

        BOOST_CHECK_EQUAL (rime::get_unsafe <int const> (v), 5);
        BOOST_CHECK_EQUAL (rime::get_unsafe <int const> (vc), 5);

        BOOST_CHECK_THROW (rime::get <int> (v), rime::bad_get);
        BOOST_CHECK_EQUAL (rime::get <int const> (v), 5);
        BOOST_CHECK_EQUAL (*rime::get <int const> (&v), 5);
    }
    {
        rime::variant <float, int> v (get_int_const());
        BOOST_CHECK_EQUAL (v.which(), 1u);
    }
    {
        rime::variant <float, const int &> v (get_int_const());
        BOOST_CHECK_EQUAL (v.which(), 0u);
    }

    // int &
    int i = 4;
    {
        variant v (i);
        BOOST_CHECK_EQUAL (v.which(), 2u);
        variant const vc (i);
        BOOST_CHECK_EQUAL (vc.which(), 2u);
        BOOST_CHECK (v.contains <int &>());
        BOOST_CHECK (!v.contains <int>());

        BOOST_CHECK_EQUAL (rime::get_unsafe <int &> (v), 4);
        BOOST_CHECK_EQUAL (rime::get <int &> (v), 4);
        BOOST_CHECK_EQUAL (&rime::get <int &> (v), &i);
        BOOST_CHECK_THROW (rime::get <int> (v), rime::bad_get);

        rime::get_unsafe <int &> (v) = 27;
        BOOST_CHECK_EQUAL (rime::get_unsafe <int &> (v), 27);
        BOOST_CHECK_EQUAL (i, 27);
        i = 4;
        BOOST_CHECK_EQUAL (rime::get_unsafe <int &> (v), 4);
    }
    {
        rime::variant <float, int, const int> v (i);
        BOOST_CHECK_EQUAL (v.which(), 1u);
        BOOST_CHECK (v.contains <int>());
    }
    {
        rime::variant <float, const int> v (i);
        BOOST_CHECK_EQUAL (v.which(), 1u);
        BOOST_CHECK (v.contains <const int>());
    }
    {
        rime::variant <float, const int &> v (i);
        // Can't be converted into const int &
        BOOST_CHECK_EQUAL (v.which(), 0u);
        BOOST_CHECK (v.contains <float>());
    }

    // int const &
    int const ic = 7;
    {
        variant v (ic);
        BOOST_CHECK_EQUAL (v.which(), 4u);
        BOOST_CHECK (v.contains <int const &>());
        variant const vc (ic);
        BOOST_CHECK_EQUAL (vc.which(), 4u);

        BOOST_CHECK_EQUAL (rime::get_unsafe <int const &> (v), 7);
        BOOST_CHECK_EQUAL (rime::get <int const &> (v), 7);
        BOOST_CHECK_THROW (rime::get <int const> (v), rime::bad_get);
        BOOST_CHECK_THROW (rime::get <int &> (v), rime::bad_get);
    }
    {
        rime::variant <float, int, const int> v (ic);
        BOOST_CHECK_EQUAL (v.which(), 2u);
        BOOST_CHECK (v.contains <const int>());
        BOOST_CHECK (!v.contains <int>());
    }
    {
        rime::variant <float, int> v (ic);
        BOOST_CHECK_EQUAL (v.which(), 1u);
        BOOST_CHECK (v.contains <int>());
        BOOST_CHECK (!v.contains <float>());
    }
    {
        rime::variant <float, int &> v (ic);
        BOOST_CHECK_EQUAL (v.which(), 0u);
    }

    // float
    float f = 3.8;
    {
        variant v (4.5f);
        BOOST_CHECK_EQUAL (v.which(), 1u);
        BOOST_CHECK (v.contains <float>());

        BOOST_CHECK_EQUAL (rime::get_unsafe <float> (v), 4.5f);
    }
    {
        variant v (f);
        BOOST_CHECK_EQUAL (v.which(), 1u);
    }
    // Ambiguous, fails at compile-time:
    /*{
        variant v (4.5);
    }*/

    // char const *
    {
        variant v ("test");
        // std::string, not a char *
        BOOST_CHECK_EQUAL (v.which(), 5u);
        BOOST_CHECK (v.contains <std::string>());

        BOOST_CHECK_EQUAL (rime::get_unsafe <std::string> (v), "test");
        BOOST_CHECK_EQUAL (rime::get <std::string> (v), "test");
        BOOST_CHECK_EQUAL (*rime::get <std::string> (&v), "test");
        BOOST_CHECK_THROW (rime::get <float> (v), rime::bad_get);
        BOOST_CHECK_EQUAL (rime::get <int> (&v), (int *) 0);

        rime::get <std::string> (v) = "test2";
        BOOST_CHECK_EQUAL (rime::get_unsafe <std::string> (v), "test2");
    }
    {
        char const * p = "test";
        variant v (p);
        // std::string, not a char *
        BOOST_CHECK_EQUAL (v.which(), 5u);
        BOOST_CHECK (v.contains <std::string>());
    }

    char c[3] = {'a', 'c', 'q'};
    // char *
    {
        char * p = &c[0];
        variant v (p);
        BOOST_CHECK_EQUAL (v.which(), 7u);
        BOOST_CHECK (v.contains <char *>());

        BOOST_CHECK (rime::get <char *> (v) == p);
        BOOST_CHECK_THROW (rime::get <void *> (v), rime::bad_get);
    }

    // void *
    {
        void * p = &c[1];
        variant v (p);
        BOOST_CHECK_EQUAL (v.which(), 6u);
        BOOST_CHECK (v.contains <void *>());
        BOOST_CHECK (!v.contains <void>());
        BOOST_CHECK_EQUAL (rime::get <void *> (v), p);
    }
    // int *
    int ia[3] = {7, 5, 10};
    {
        int * p = &ia[0];
        variant v (p);
        BOOST_CHECK_EQUAL (v.which(), 6u);
        BOOST_CHECK (v.contains <void *>());
        BOOST_CHECK_EQUAL (rime::get <void *> (v), p);
    }

    // converted
    {
        variant v (std::move (converted()));
        BOOST_CHECK_EQUAL (v.which(), 8u);
        BOOST_CHECK (v.contains <converted>());
    }
    {
        converted c;
        variant v (c);
        BOOST_CHECK_EQUAL (v.which(), 8u);
        BOOST_CHECK (v.contains <converted>());
    }
    // convertee
    {
        variant v (std::move (convertee()));
        BOOST_CHECK_EQUAL (v.which(), 8u);
        BOOST_CHECK (v.contains <converted>());
    }
    {
        convertee c;
        variant v (c);
        BOOST_CHECK_EQUAL (v.which(), 8u);
        BOOST_CHECK (v.contains <converted>());
    }

    // void
    {
        variant v;
        BOOST_CHECK_EQUAL (v.which(), 9u);
        BOOST_CHECK (v.contains <void>());
        BOOST_CHECK (!v.contains <void *>());
        rime::get <void> (v);
        // It's not clear that it makes sense to return a void * with a
        // meaningless value, but it makes it easier to write generic code.
        rime::get <void> (&v);
    }
}

BOOST_AUTO_TEST_CASE (test_rime_variant_move_construct) {
    /*
    rime:variant is geared towards unifying return values.
    Essentially, this means a stack of return values.
    This uses move construction throughout.
    Move construction from variants with the same type parameters should
    retain the type exactly.
    Move construction from const variants (as opposed to a variant with const
    content) can add a "const" qualifier to the contained type.
    */

    // 0 int
    {
        // Sanity
        BOOST_CHECK_EQUAL (make_variant (7).which(), 0u);
        BOOST_CHECK_EQUAL (make_const_variant (13).which(), 0u);

        variant moved (make_variant (7));
        BOOST_CHECK_EQUAL (moved.which(), 0u);
        BOOST_CHECK_EQUAL (rime::get <int> (moved), 7);

        variant moved_const (make_const_variant (13));
        BOOST_CHECK_EQUAL (moved_const.which(), 3u);
        BOOST_CHECK_EQUAL (rime::get <int const> (moved_const), 13);
    }
    {
        // From other variant type
        BOOST_CHECK_EQUAL (make_other_variant (7).which(), 0u);
        BOOST_CHECK_EQUAL (make_const_other_variant (13).which(), 0u);

        variant moved (make_other_variant (7));
        BOOST_CHECK_EQUAL (moved.which(), 0u);
        BOOST_CHECK_EQUAL (rime::get <int> (moved), 7);

        variant moved_const (make_const_other_variant (13));
        BOOST_CHECK_EQUAL (moved_const.which(), 3u);
        BOOST_CHECK_EQUAL (rime::get <int const> (moved_const), 13);
    }

    // 1 float
    {
        // Sanity
        BOOST_CHECK_EQUAL (make_variant (7.3f).which(), 1u);
        BOOST_CHECK_EQUAL (make_const_variant (7.3f).which(), 1u);

        // Move construction
        variant moved (make_variant (7.3f));
        BOOST_CHECK_EQUAL (moved.which(), 1u);
        BOOST_CHECK_EQUAL (rime::get <float> (moved), 7.3f);

        variant moved_const (make_const_variant (7.3f));
        BOOST_CHECK_EQUAL (moved_const.which(), 1u);
        BOOST_CHECK_EQUAL (rime::get <float> (moved_const), 7.3f);
    }
    {
        // From other variant type
        BOOST_CHECK_EQUAL (make_other_variant (7.3f).which(), 1u);
        BOOST_CHECK_EQUAL (make_const_other_variant (7.3f).which(), 1u);

        variant moved (make_other_variant (7.3f));
        BOOST_CHECK_EQUAL (moved.which(), 1u);
        BOOST_CHECK_EQUAL (rime::get <float> (moved), 7.3f);

        variant moved_const (make_const_other_variant (7.3f));
        BOOST_CHECK_EQUAL (moved_const.which(), 1u);
        BOOST_CHECK_EQUAL (rime::get <float> (moved_const), 7.3f);
    }

    // 2 int &
    {
        int i = 4;
        // Sanity
        BOOST_CHECK_EQUAL (make_variant (i).which(), 2u);
        BOOST_CHECK_EQUAL (make_const_variant (i).which(), 2u);

        variant moved (make_variant (i));
        BOOST_CHECK_EQUAL (moved.which(), 2u);
        BOOST_CHECK_EQUAL (rime::get <int &> (moved), 4);

        variant moved_const (make_const_variant (i));
        BOOST_CHECK_EQUAL (moved_const.which(), 2u);
        BOOST_CHECK_EQUAL (rime::get <int &> (moved_const), 4);
    }
    {
        // From other variant type
        int i = 4;
        BOOST_CHECK_EQUAL (make_other_variant (i).which(), 2u);
        BOOST_CHECK_EQUAL (make_const_other_variant (i).which(), 2u);

        variant moved (make_other_variant (i));
        BOOST_CHECK_EQUAL (moved.which(), 2u);
        BOOST_CHECK_EQUAL (rime::get <int &> (moved), 4);

        variant moved_const (make_const_other_variant (i));
        BOOST_CHECK_EQUAL (moved_const.which(), 2u);
        BOOST_CHECK_EQUAL (rime::get <int &> (moved_const), 4);
    }

    // 3 int const
    {
        // Sanity
        BOOST_CHECK_EQUAL (make_variant (get_int_const()).which(), 3u);
        BOOST_CHECK_EQUAL (make_const_variant (get_int_const()).which(), 3u);

        // Move construction
        variant moved (make_variant (get_int_const()));
        BOOST_CHECK_EQUAL (moved.which(), 3u);
        BOOST_CHECK_EQUAL (rime::get <int const> (moved), 5);

        variant moved_const (make_const_variant (get_int_const()));
        BOOST_CHECK_EQUAL (moved_const.which(), 3u);
        BOOST_CHECK_EQUAL (rime::get <int const> (moved_const), 5);
    }
    {
        // From other variant type
        BOOST_CHECK_EQUAL (make_other_variant (get_int_const()).which(), 3u);
        BOOST_CHECK_EQUAL (make_const_other_variant (get_int_const()).which(),
            3u);

        variant moved (make_other_variant (get_int_const()));
        BOOST_CHECK_EQUAL (moved.which(), 3u);
        BOOST_CHECK_EQUAL (rime::get <int const> (moved), 5);

        variant moved_const (make_const_other_variant (get_int_const()));
        BOOST_CHECK_EQUAL (moved_const.which(), 3u);
        BOOST_CHECK_EQUAL (rime::get <int const> (moved_const), 5);
    }

    // 4 int const &
    {
        int const ic = 7;
        // Sanity
        BOOST_CHECK_EQUAL (make_variant (ic).which(), 4u);
        BOOST_CHECK_EQUAL (make_const_variant (ic).which(), 4u);

        variant moved (make_variant (ic));
        BOOST_CHECK_EQUAL (moved.which(), 4u);
        BOOST_CHECK_EQUAL (rime::get <int const &> (moved), 7);
        BOOST_CHECK_EQUAL (&rime::get <int const &> (moved), &ic);

        variant moved_const (make_const_variant (ic));
        BOOST_CHECK_EQUAL (moved_const.which(), 4u);
        BOOST_CHECK_EQUAL (&rime::get <int const &> (moved_const), &ic);
    }
    {
        // From other variant type
        int const ic = 7;
        BOOST_CHECK_EQUAL (make_other_variant (ic).which(), 4u);
        BOOST_CHECK_EQUAL (make_const_other_variant (ic).which(), 4u);

        variant moved (make_other_variant (ic));
        BOOST_CHECK_EQUAL (moved.which(), 4u);
        BOOST_CHECK_EQUAL (rime::get <int const &> (moved), 7);
        BOOST_CHECK_EQUAL (&rime::get <int const &> (moved), &ic);

        variant moved_const (make_const_other_variant (ic));
        BOOST_CHECK_EQUAL (moved_const.which(), 4u);
        BOOST_CHECK_EQUAL (&rime::get <int const &> (moved_const), &ic);
    }

    // 5 std::string
    {
        // Sanity
        BOOST_CHECK_EQUAL (make_variant (std::string ("Hello")).which(), 5u);
        BOOST_CHECK_EQUAL (make_const_variant (std::string ("Hello")).which(),
            5u);

        // Move construction
        variant moved (make_variant (std::string ("Hello")));
        BOOST_CHECK_EQUAL (moved.which(), 5u);
        BOOST_CHECK_EQUAL (rime::get <std::string> (moved), "Hello");

        variant moved_const (make_const_variant (std::string ("Hello")));
        BOOST_CHECK_EQUAL (moved_const.which(), 5u);
        BOOST_CHECK_EQUAL (rime::get <std::string> (moved_const), "Hello");
    }

    // 6 void *
    {
        int i = 7;
        // Sanity
        BOOST_CHECK_EQUAL (make_variant (&i).which(), 6u);
        BOOST_CHECK_EQUAL (make_const_variant (&i).which(), 6u);

        // Move construction
        variant moved (make_variant (&i));
        BOOST_CHECK_EQUAL (moved.which(), 6u);
        BOOST_CHECK_EQUAL (rime::get <void *> (moved), &i);

        variant moved_const (make_const_variant (&i));
        BOOST_CHECK_EQUAL (moved_const.which(), 6u);
        BOOST_CHECK_EQUAL (rime::get <void *> (moved_const), &i);
    }

    // 7 char *
    {
        char c = 'A';
        // Sanity
        BOOST_CHECK_EQUAL (make_variant (&c).which(), 7u);
        BOOST_CHECK_EQUAL (make_const_variant (&c).which(), 7u);

        // Move construction
        variant moved (make_variant (&c));
        BOOST_CHECK_EQUAL (moved.which(), 7u);
        BOOST_CHECK (rime::get <char *> (moved) == &c);

        variant moved_const (make_const_variant (&c));
        BOOST_CHECK_EQUAL (moved_const.which(), 7u);
        BOOST_CHECK (rime::get <char *> (moved_const) == &c);
    }

    // 8 converted
    {
        // Sanity
        BOOST_CHECK_EQUAL (make_variant (converted()).which(), 8u);
        BOOST_CHECK_EQUAL (make_const_variant (converted()).which(), 8u);

        // Move construction
        variant moved (make_variant (converted()));
        BOOST_CHECK_EQUAL (moved.which(), 8u);
        rime::get <converted> (moved);

        variant moved_const (make_const_variant (converted()));
        BOOST_CHECK_EQUAL (moved_const.which(), 8u);
        rime::get <converted> (moved_const);
    }
    // 9 void
    {
        // Sanity
        BOOST_CHECK_EQUAL (make_variant().which(), 9u);
        BOOST_CHECK_EQUAL (make_const_variant().which(), 9u);

        // Move construction
        variant moved (make_variant());
        BOOST_CHECK_EQUAL (moved.which(), 9u);

        variant moved_const (make_const_variant());
        BOOST_CHECK_EQUAL (moved_const.which(), 9u);
    }
}

BOOST_AUTO_TEST_CASE (test_rime_variant_copy_construct) {
    // 0 int
    {
        variant v (7);
        variant const vc (7);
        // Sanity
        BOOST_CHECK_EQUAL (v.which(), 0u);
        BOOST_CHECK_EQUAL (vc.which(), 0u);

        // int becomes int const &.
        variant copied (v);
        BOOST_CHECK_EQUAL (copied.which(), 4u);
        BOOST_CHECK_EQUAL (rime::get <int const &> (copied), 7);
        // And the original int can be edited.
        rime::get <int> (v) = 10;
        BOOST_CHECK_EQUAL (rime::get <int const &> (copied), 10);

        variant copied_const (vc);
        BOOST_CHECK_EQUAL (copied_const.which(), 4u);
        BOOST_CHECK_EQUAL (rime::get <int const &> (copied_const), 7);
    }
    {
        // From other variant type
        other_variant v (7);
        other_variant const vc (7);
        BOOST_CHECK_EQUAL (v.which(), 0u);
        BOOST_CHECK_EQUAL (vc.which(), 0u);

        variant copied (v);
        BOOST_CHECK_EQUAL (copied.which(), 4u);
        BOOST_CHECK_EQUAL (rime::get <int const &> (copied), 7);
        rime::get <int> (v) = 10;
        BOOST_CHECK_EQUAL (rime::get <int const &> (copied), 10);

        variant copied_const (vc);
        BOOST_CHECK_EQUAL (copied_const.which(), 4u);
        BOOST_CHECK_EQUAL (rime::get <int const &> (copied_const), 7);
    }

    // 1 float
    {
        variant v (7.3f);
        variant const vc (7.3f);
        // Sanity
        BOOST_CHECK_EQUAL (v.which(), 1u);
        BOOST_CHECK_EQUAL (vc.which(), 1u);

        // float becomes float.
        variant copied (v);
        BOOST_CHECK_EQUAL (copied.which(), 1u);
        BOOST_CHECK_EQUAL (rime::get <float> (copied), 7.3f);

        variant copied_const (vc);
        BOOST_CHECK_EQUAL (copied_const.which(), 1u);
        BOOST_CHECK_EQUAL (rime::get <float> (copied_const), 7.3f);
    }
    {
        // From other variant type
        other_variant v (7.3f);
        other_variant const vc (7.3f);
        BOOST_CHECK_EQUAL (v.which(), 1u);
        BOOST_CHECK_EQUAL (vc.which(), 1u);

        variant copied (v);
        BOOST_CHECK_EQUAL (copied.which(), 1u);
        BOOST_CHECK_EQUAL (rime::get <float> (copied), 7.3f);

        variant copied_const (vc);
        BOOST_CHECK_EQUAL (copied_const.which(), 1u);
        BOOST_CHECK_EQUAL (rime::get <float> (copied_const), 7.3f);
    }

    // 2 int &
    {
        int i = 4;
        variant v (i);
        variant const vc (i);
        // Sanity
        BOOST_CHECK_EQUAL (v.which(), 2u);
        BOOST_CHECK_EQUAL (vc.which(), 2u);

        // int & remains int &.
        variant copied (v);
        BOOST_CHECK_EQUAL (copied.which(), 2u);
        BOOST_CHECK_EQUAL (rime::get <int &> (copied), 4);
        BOOST_CHECK_EQUAL (&rime::get <int &> (copied), &i);

        variant copied_const (vc);
        BOOST_CHECK_EQUAL (copied_const.which(), 2u);
        BOOST_CHECK_EQUAL (&rime::get <int &> (copied_const), &i);
    }
    {
        // From other variant type
        int i = 4;
        other_variant v (i);
        other_variant const vc (i);
        BOOST_CHECK_EQUAL (v.which(), 2u);
        BOOST_CHECK_EQUAL (vc.which(), 2u);

        variant copied (v);
        BOOST_CHECK_EQUAL (copied.which(), 2u);
        BOOST_CHECK_EQUAL (rime::get <int &> (copied), 4);
        BOOST_CHECK_EQUAL (&rime::get <int &> (copied), &i);

        variant copied_const (vc);
        BOOST_CHECK_EQUAL (copied_const.which(), 2u);
        BOOST_CHECK_EQUAL (&rime::get <int &> (copied_const), &i);
    }

    // 3 int const
    {
        variant v (get_int_const());
        variant const vc (get_int_const());
        // Sanity
        BOOST_CHECK_EQUAL (v.which(), 3u);
        BOOST_CHECK_EQUAL (vc.which(), 3u);

        // Copy construction: int const becomes int const & pointing to the
        // original int const.
        variant copied (v);
        BOOST_CHECK_EQUAL (copied.which(), 4u);
        BOOST_CHECK_EQUAL (rime::get <int const &> (copied), 5);
        BOOST_CHECK_EQUAL (&rime::get <int const &> (copied),
            &rime::get <int const> (v));

        variant copied_const (vc);
        BOOST_CHECK_EQUAL (copied_const.which(), 4u);
        BOOST_CHECK_EQUAL (rime::get <int const &> (copied_const), 5);
        BOOST_CHECK_EQUAL (&rime::get <int const &> (copied_const),
            &rime::get <int const> (vc));
    }
    {
        // From other variant type
        other_variant v (get_int_const());
        other_variant const vc (get_int_const());
        BOOST_CHECK_EQUAL (v.which(), 3u);
        BOOST_CHECK_EQUAL (vc.which(), 3u);

        variant copied (v);
        BOOST_CHECK_EQUAL (copied.which(), 4u);
        BOOST_CHECK_EQUAL (rime::get <int const &> (copied), 5);
        BOOST_CHECK_EQUAL (&rime::get <int const &> (copied),
            &rime::get <int const> (v));

        variant copied_const (vc);
        BOOST_CHECK_EQUAL (copied_const.which(), 4u);
        BOOST_CHECK_EQUAL (rime::get <int const &> (copied_const), 5);
        BOOST_CHECK_EQUAL (&rime::get <int const &> (copied_const),
            &rime::get <int const> (vc));
    }

    // 4 int const &
    {
        int const ic = 12;
        variant v (ic);
        variant const vc (ic);
        // Sanity
        BOOST_CHECK_EQUAL (v.which(), 4u);
        BOOST_CHECK_EQUAL (vc.which(), 4u);

        // int const & remains int const &.
        variant copied (v);
        BOOST_CHECK_EQUAL (copied.which(), 4u);
        BOOST_CHECK_EQUAL (&rime::get <int const &> (copied), &ic);

        variant copied_const (vc);
        BOOST_CHECK_EQUAL (copied_const.which(), 4u);
        BOOST_CHECK_EQUAL (&rime::get <int const &> (copied_const), &ic);
    }
    {
        // From other variant type
        int const ic = 12;
        other_variant v (ic);
        other_variant const vc (ic);
        BOOST_CHECK_EQUAL (v.which(), 4u);
        BOOST_CHECK_EQUAL (vc.which(), 4u);

        variant copied (v);
        BOOST_CHECK_EQUAL (copied.which(), 4u);
        BOOST_CHECK_EQUAL (&rime::get <int const &> (copied), &ic);

        variant copied_const (vc);
        BOOST_CHECK_EQUAL (copied_const.which(), 4u);
        BOOST_CHECK_EQUAL (&rime::get <int const &> (copied_const), &ic);
    }

    // 5 std::string
    {
        variant v (std::string ("Hello"));
        variant const vc (std::string ("Hello"));
        // Sanity
        BOOST_CHECK_EQUAL (v.which(), 5u);
        BOOST_CHECK_EQUAL (vc.which(), 5u);

        // float becomes float.
        variant copied (v);
        BOOST_CHECK_EQUAL (copied.which(), 5u);
        BOOST_CHECK_EQUAL (rime::get <std::string> (copied), "Hello");

        variant copied_const (vc);
        BOOST_CHECK_EQUAL (copied_const.which(), 5u);
        BOOST_CHECK_EQUAL (rime::get <std::string> (copied_const), "Hello");
    }

    // 6 void *
    {
        int i = 7;
        variant v (&i);
        variant const vc (&i);
        // Sanity
        BOOST_CHECK_EQUAL (v.which(), 6u);
        BOOST_CHECK_EQUAL (vc.which(), 6u);

        // float becomes float.
        variant copied (v);
        BOOST_CHECK_EQUAL (copied.which(), 6u);
        BOOST_CHECK_EQUAL (rime::get <void *> (copied), &i);

        variant copied_const (vc);
        BOOST_CHECK_EQUAL (copied_const.which(), 6u);
        BOOST_CHECK_EQUAL (rime::get <void *> (copied_const), &i);
    }

    // 7 char *
    {
        char c = 7;
        variant v (&c);
        variant const vc (&c);
        // Sanity
        BOOST_CHECK_EQUAL (v.which(), 7u);
        BOOST_CHECK_EQUAL (vc.which(), 7u);

        // float becomes float.
        variant copied (v);
        BOOST_CHECK_EQUAL (copied.which(), 7u);
        BOOST_CHECK (rime::get <char *> (copied) == &c);

        variant copied_const (vc);
        BOOST_CHECK_EQUAL (copied_const.which(), 7u);
        BOOST_CHECK (rime::get <char *> (copied_const) == &c);
    }

    // 8 converted
    {
        converted c;
        variant v (c);
        variant const vc (c);
        // Sanity
        BOOST_CHECK_EQUAL (v.which(), 8u);
        BOOST_CHECK_EQUAL (vc.which(), 8u);

        // float becomes float.
        variant copied (v);
        BOOST_CHECK_EQUAL (copied.which(), 8u);
        rime::get <converted> (copied);

        variant copied_const (vc);
        BOOST_CHECK_EQUAL (copied_const.which(), 8u);
        rime::get <converted> (copied_const);
    }

    // 9 void
    {
        variant v;
        variant const vc;
        // Sanity
        BOOST_CHECK_EQUAL (v.which(), 9u);
        BOOST_CHECK_EQUAL (vc.which(), 9u);

        variant copied (v);
        BOOST_CHECK_EQUAL (copied.which(), 9u);

        variant copied_const (vc);
        BOOST_CHECK_EQUAL (copied_const.which(), 9u);
    }
}

struct tracked_assignable {
    tracked_assignable & operator = (utility::tracked<> const &)
    { return *this; }
};

template <typename Variant, typename Variant2>
    void test_rime_variant_objects_tracked()
{
    using utility::tracked;
    // Construction and destruction
    {
        utility::tracked_registry registry;
        {
            Variant v = tracked<> (registry);
        }
        BOOST_CHECK_EQUAL (registry.value_construct_count(), 1);
        BOOST_CHECK_EQUAL (registry.move_count(), 1);
        BOOST_CHECK_EQUAL (registry.destruct_count(), 1);
        BOOST_CHECK_EQUAL (registry.destruct_moved_count(), 1);
        BOOST_CHECK (registry.consistent());
    }
    // Copy-construction
    {
        utility::tracked_registry registry;
        {
            tracked<> c (registry);
            // Copy-construct v from c

            Variant v (c);
            BOOST_CHECK_EQUAL (registry.copy_count(), 1);

            // Copy-construct v2 from v.
            // Underneath, this should copy-construct the tracked in v2 from
            // the tracked in v.
            Variant2 v2 (v);
            BOOST_CHECK_EQUAL (registry.copy_count(), 2);
        }
        BOOST_CHECK_EQUAL (registry.value_construct_count(), 1);
        BOOST_CHECK_EQUAL (registry.move_count(), 0);
        BOOST_CHECK_EQUAL (registry.copy_count(), 2);
        BOOST_CHECK_EQUAL (registry.destruct_count(), 3);
        BOOST_CHECK_EQUAL (registry.destruct_moved_count(), 0);
        BOOST_CHECK (registry.consistent());
    }

    // Move-construction
    {
        utility::tracked_registry registry;
        {
            tracked<> c (registry);
            BOOST_CHECK_EQUAL (registry.copy_count(), 0);

            // Move-construct v from c
            Variant v (std::move (c));
            BOOST_CHECK_EQUAL (registry.copy_count(), 0);
            BOOST_CHECK_EQUAL (registry.move_count(), 1);

            // Move-construct v2 from v.
            // Underneath, this should move-construct the tracked in v2 from
            // the tracked in v.
            Variant2 v2 (std::move (v));
            BOOST_CHECK_EQUAL (registry.copy_count(), 0);
            BOOST_CHECK_EQUAL (registry.move_count(), 2);
        }
        BOOST_CHECK_EQUAL (registry.value_construct_count(), 1);
        BOOST_CHECK_EQUAL (registry.move_count(), 2);
        BOOST_CHECK_EQUAL (registry.copy_count(), 0);
        BOOST_CHECK_EQUAL (registry.destruct_count(), 1);
        BOOST_CHECK_EQUAL (registry.destruct_moved_count(), 2);
        BOOST_CHECK (registry.consistent());
    }

    // Move get.
    // If the variant is a temporary, "get" should return an rvalue reference.
    {
        utility::tracked_registry registry;
        {
            tracked<> c (registry);
            BOOST_CHECK_EQUAL (registry.copy_count(), 0);

            Variant v (std::move (c));
            // Sanity check; see previous test.
            BOOST_CHECK_EQUAL (registry.copy_count(), 0);
            BOOST_CHECK_EQUAL (registry.move_count(), 1);

            // get
            tracked<> c2 (rime::get <tracked<>> (std::move (v)));
            BOOST_CHECK_EQUAL (registry.copy_count(), 0);
            BOOST_CHECK_EQUAL (registry.move_count(), 2);

            Variant v2 (std::move (c2));
            // unsafe_get
            tracked<> c3 (rime::get_unsafe <tracked<>> (std::move (v2)));
            BOOST_CHECK_EQUAL (registry.copy_count(), 0);
            BOOST_CHECK_EQUAL (registry.move_count(), 4);
        }
        BOOST_CHECK_EQUAL (registry.value_construct_count(), 1);
        BOOST_CHECK_EQUAL (registry.move_count(), 4);
        BOOST_CHECK_EQUAL (registry.copy_count(), 0);
        BOOST_CHECK_EQUAL (registry.destruct_count(), 1);
        BOOST_CHECK_EQUAL (registry.destruct_moved_count(), 4);
        BOOST_CHECK (registry.consistent());
    }
}

// Test construction, destruction, copying, moving
BOOST_AUTO_TEST_CASE (test_rime_variant_objects) {
    typedef rime::variant <utility::tracked<>, int> variant1;
    typedef rime::variant <int, utility::tracked<>> variant2;
    typedef rime::variant <utility::tracked<>> variant3;
    typedef rime::variant <int, utility::tracked<>, float> variant4;

    test_rime_variant_objects_tracked <variant1, variant1>();
    test_rime_variant_objects_tracked <variant2, variant2>();
    test_rime_variant_objects_tracked <variant3, variant3>();
    test_rime_variant_objects_tracked <variant4, variant4>();

    test_rime_variant_objects_tracked <variant1, variant2>();
    test_rime_variant_objects_tracked <variant3, variant4>();
    test_rime_variant_objects_tracked <variant4, variant1>();

    test_rime_variant_objects_tracked <variant2, variant4>();
    test_rime_variant_objects_tracked <variant3, variant1>();
    test_rime_variant_objects_tracked <variant4, variant2>();

    test_rime_variant_objects_tracked <variant1, variant4>();
    test_rime_variant_objects_tracked <variant2, variant1>();
    test_rime_variant_objects_tracked <variant3, variant2>();

    // Moving from references.
    {
        utility::tracked_registry registry;
        {
            utility::tracked<> c (registry);
            rime::variant <utility::tracked<> &, int> v (c);
            BOOST_CHECK_EQUAL (registry.value_construct_count(), 1);
            BOOST_CHECK_EQUAL (registry.copy_count(), 0);

            variant1 v2 (std::move (v));
            // c must be unaffected and not moved, just copied.
            BOOST_CHECK_EQUAL (registry.value_construct_count(), 1);
            BOOST_CHECK_EQUAL (registry.move_count(), 0);
            BOOST_CHECK_EQUAL (registry.copy_count(), 1);
        }
        BOOST_CHECK_EQUAL (registry.destruct_count(), 2);
        BOOST_CHECK (registry.consistent());
    }
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: rogiervd/rime

max_issues_repo_name: rogiervd/rime

max_forks_repo_name: rogiervd/rime


text:
/*=============================================================================
    Copyright (c) 2001-2007 Joel de Guzman

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#ifndef PHOENIX_CORE_REFERENCE_HPP
#define PHOENIX_CORE_REFERENCE_HPP

#include <boost/spirit/home/phoenix/core/actor.hpp>
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_reference.hpp>
#include <boost/mpl/bool.hpp>

namespace boost { namespace phoenix
{
    template <typename T>
    struct reference
    {
        // $$$ TODO: a better (user friendly) static assert
        BOOST_STATIC_ASSERT(
            mpl::not_<is_reference<T> >::value != 0);

        typedef mpl::false_ no_nullary;

        template <typename Env>
        struct result
        {
            typedef T& type;
        };

        reference(T& arg)
            : ref(arg) {}

        template <typename Env>
        T& eval(Env const&) const
        {
            return ref;
        }

        T& ref;

    private:
        // silence MSVC warning C4512: assignment operator could not be generated
        reference& operator= (reference const&);
    };

    template <typename T>
    inline actor<reference<T> > const
    ref(T& v)
    {
        return reference<T>(v);
    }

    template <typename T>
    inline actor<reference<T const> > const
    cref(T const& v)
    {
        return reference<T const>(v);
    }

    namespace detail
    {
        struct error_attempting_to_convert_an_actor_to_a_reference {};
    }

    template <typename Base>
    void
    ref(actor<Base> const& v
        , detail::error_attempting_to_convert_an_actor_to_a_reference
            = detail::error_attempting_to_convert_an_actor_to_a_reference());

    template <typename Base>
    void
    cref(actor<Base> const& v
        , detail::error_attempting_to_convert_an_actor_to_a_reference
            = detail::error_attempting_to_convert_an_actor_to_a_reference());
}}

#endif

max_stars_repo_name: importlib/klib

max_issues_repo_name: isuhao/klib

max_forks_repo_name: isuhao/klib