text:
/////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga  2013-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)
//
// See http://www.boost.org/libs/intrusive for documentation.
//
/////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_INTRUSIVE_BS_SET_HPP
#define BOOST_INTRUSIVE_BS_SET_HPP

#if defined(_MSC_VER)
#  pragma once
#endif

#include <boost/intrusive/detail/config_begin.hpp>
#include <boost/intrusive/intrusive_fwd.hpp>
#include <boost/intrusive/detail/mpl.hpp>
#include <boost/intrusive/bstree.hpp>
#include <boost/move/utility_core.hpp>
#include <boost/static_assert.hpp>

namespace boost {
namespace intrusive {

//! The class template bs_set is an intrusive container, that mimics most of
//! the interface of std::set as described in the C++ standard.
//!
//! The template parameter \c T is the type to be managed by the container.
//! The user can specify additional options and if no options are provided
//! default options are used.
//!
//! The container supports the following options:
//! \c base_hook<>/member_hook<>/value_traits<>,
//! \c constant_time_size<>, \c size_type<> and
//! \c compare<>.
#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED)
template<class T, class ...Options>
#else
template<class ValueTraits, class Compare, class SizeType, bool ConstantTimeSize, typename HeaderHolder>
#endif
class bs_set_impl
#ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED
   : public bstree_impl<ValueTraits, Compare, SizeType, ConstantTimeSize, BsTreeAlgorithms, HeaderHolder>
#endif
{
   /// @cond
   typedef bstree_impl<ValueTraits, Compare, SizeType, ConstantTimeSize, BsTreeAlgorithms, HeaderHolder> tree_type;
   BOOST_MOVABLE_BUT_NOT_COPYABLE(bs_set_impl)

   typedef tree_type implementation_defined;
   /// @endcond

   public:
   typedef typename implementation_defined::value_type               value_type;
   typedef typename implementation_defined::value_traits             value_traits;
   typedef typename implementation_defined::pointer                  pointer;
   typedef typename implementation_defined::const_pointer            const_pointer;
   typedef typename implementation_defined::reference                reference;
   typedef typename implementation_defined::const_reference          const_reference;
   typedef typename implementation_defined::difference_type          difference_type;
   typedef typename implementation_defined::size_type                size_type;
   typedef typename implementation_defined::value_compare            value_compare;
   typedef typename implementation_defined::key_compare              key_compare;
   typedef typename implementation_defined::iterator                 iterator;
   typedef typename implementation_defined::const_iterator           const_iterator;
   typedef typename implementation_defined::reverse_iterator         reverse_iterator;
   typedef typename implementation_defined::const_reverse_iterator   const_reverse_iterator;
   typedef typename implementation_defined::insert_commit_data       insert_commit_data;
   typedef typename implementation_defined::node_traits              node_traits;
   typedef typename implementation_defined::node                     node;
   typedef typename implementation_defined::node_ptr                 node_ptr;
   typedef typename implementation_defined::const_node_ptr           const_node_ptr;
   typedef typename implementation_defined::node_algorithms          node_algorithms;

   static const bool constant_time_size = tree_type::constant_time_size;

   public:
   //! @copydoc ::boost::intrusive::bstree::bstree(const value_compare &,const value_traits &)
   explicit bs_set_impl( const value_compare &cmp = value_compare()
                    , const value_traits &v_traits = value_traits())
      :  tree_type(cmp, v_traits)
   {}

   //! @copydoc ::boost::intrusive::bstree::bstree(bool,Iterator,Iterator,const value_compare &,const value_traits &)
   template<class Iterator>
   bs_set_impl( Iterator b, Iterator e
           , const value_compare &cmp = value_compare()
           , const value_traits &v_traits = value_traits())
      : tree_type(true, b, e, cmp, v_traits)
   {}

   //! @copydoc ::boost::intrusive::bstree::bstree(bstree &&)
   bs_set_impl(BOOST_RV_REF(bs_set_impl) x)
      :  tree_type(::boost::move(static_cast<tree_type&>(x)))
   {}

   //! @copydoc ::boost::intrusive::bstree::operator=(bstree &&)
   bs_set_impl& operator=(BOOST_RV_REF(bs_set_impl) x)
   {  return static_cast<bs_set_impl&>(tree_type::operator=(::boost::move(static_cast<tree_type&>(x)))); }

   #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED
   //! @copydoc ::boost::intrusive::bstree::~bstree()
   ~bs_set_impl();

   //! @copydoc ::boost::intrusive::bstree::begin()
   iterator begin();

   //! @copydoc ::boost::intrusive::bstree::begin()const
   const_iterator begin() const;

   //! @copydoc ::boost::intrusive::bstree::cbegin()const
   const_iterator cbegin() const;

   //! @copydoc ::boost::intrusive::bstree::end()
   iterator end();

   //! @copydoc ::boost::intrusive::bstree::end()const
   const_iterator end() const;

   //! @copydoc ::boost::intrusive::bstree::cend()const
   const_iterator cend() const;

   //! @copydoc ::boost::intrusive::bstree::rbegin()
   reverse_iterator rbegin();

   //! @copydoc ::boost::intrusive::bstree::rbegin()const
   const_reverse_iterator rbegin() const;

   //! @copydoc ::boost::intrusive::bstree::crbegin()const
   const_reverse_iterator crbegin() const;

   //! @copydoc ::boost::intrusive::bstree::rend()
   reverse_iterator rend();

   //! @copydoc ::boost::intrusive::bstree::rend()const
   const_reverse_iterator rend() const;

   //! @copydoc ::boost::intrusive::bstree::crend()const
   const_reverse_iterator crend() const;

   //! @copydoc ::boost::intrusive::bstree::container_from_end_iterator(iterator)
   static bs_set_impl &container_from_end_iterator(iterator end_iterator);

   //! @copydoc ::boost::intrusive::bstree::container_from_end_iterator(const_iterator)
   static const bs_set_impl &container_from_end_iterator(const_iterator end_iterator);

   //! @copydoc ::boost::intrusive::bstree::container_from_iterator(iterator)
   static bs_set_impl &container_from_iterator(iterator it);

   //! @copydoc ::boost::intrusive::bstree::container_from_iterator(const_iterator)
   static const bs_set_impl &container_from_iterator(const_iterator it);

   //! @copydoc ::boost::intrusive::bstree::key_comp()const
   key_compare key_comp() const;

   //! @copydoc ::boost::intrusive::bstree::value_comp()const
   value_compare value_comp() const;

   //! @copydoc ::boost::intrusive::bstree::empty()const
   bool empty() const;

   //! @copydoc ::boost::intrusive::bstree::size()const
   size_type size() const;

   //! @copydoc ::boost::intrusive::bstree::swap
   void swap(bs_set_impl& other);

   //! @copydoc ::boost::intrusive::bstree::clone_from
   template <class Cloner, class Disposer>
   void clone_from(const bs_set_impl &src, Cloner cloner, Disposer disposer);

   #endif   //#ifdef BOOST_iNTRUSIVE_DOXYGEN_INVOKED

   //! @copydoc ::boost::intrusive::bstree::insert_unique(reference)
   std::pair<iterator, bool> insert(reference value)
   {  return tree_type::insert_unique(value);  }

   //! @copydoc ::boost::intrusive::bstree::insert_unique(const_iterator,reference)
   iterator insert(const_iterator hint, reference value)
   {  return tree_type::insert_unique(hint, value);  }

   //! @copydoc ::boost::intrusive::bstree::insert_unique_check(const KeyType&,KeyValueCompare,insert_commit_data&)
   template<class KeyType, class KeyValueCompare>
   std::pair<iterator, bool> insert_check
      (const KeyType &key, KeyValueCompare key_value_comp, insert_commit_data &commit_data)
   {  return tree_type::insert_unique_check(key, key_value_comp, commit_data); }

   //! @copydoc ::boost::intrusive::bstree::insert_unique_check(const_iterator,const KeyType&,KeyValueCompare,insert_commit_data&)
   template<class KeyType, class KeyValueCompare>
   std::pair<iterator, bool> insert_check
      (const_iterator hint, const KeyType &key
      ,KeyValueCompare key_value_comp, insert_commit_data &commit_data)
   {  return tree_type::insert_unique_check(hint, key, key_value_comp, commit_data); }

   //! @copydoc ::boost::intrusive::bstree::insert_unique(Iterator,Iterator)
   template<class Iterator>
   void insert(Iterator b, Iterator e)
   {  tree_type::insert_unique(b, e);  }

   //! @copydoc ::boost::intrusive::bstree::insert_unique_commit
   iterator insert_commit(reference value, const insert_commit_data &commit_data)
   {  return tree_type::insert_unique_commit(value, commit_data);  }

   #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED
   //! @copydoc ::boost::intrusive::bstree::insert_before
   iterator insert_before(const_iterator pos, reference value);

   //! @copydoc ::boost::intrusive::bstree::push_back
   void push_back(reference value);

   //! @copydoc ::boost::intrusive::bstree::push_front
   void push_front(reference value);

   //! @copydoc ::boost::intrusive::bstree::erase(const_iterator)
   iterator erase(const_iterator i);

   //! @copydoc ::boost::intrusive::bstree::erase(const_iterator,const_iterator)
   iterator erase(const_iterator b, const_iterator e);

   //! @copydoc ::boost::intrusive::bstree::erase(const_reference)
   size_type erase(const_reference value);

   //! @copydoc ::boost::intrusive::bstree::erase(const KeyType&,KeyValueCompare)
   template<class KeyType, class KeyValueCompare>
   size_type erase(const KeyType& key, KeyValueCompare comp);

   //! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const_iterator,Disposer)
   template<class Disposer>
   iterator erase_and_dispose(const_iterator i, Disposer disposer);

   //! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const_iterator,const_iterator,Disposer)
   template<class Disposer>
   iterator erase_and_dispose(const_iterator b, const_iterator e, Disposer disposer);

   //! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const_reference, Disposer)
   template<class Disposer>
   size_type erase_and_dispose(const_reference value, Disposer disposer);

   //! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const KeyType&,KeyValueCompare,Disposer)
   template<class KeyType, class KeyValueCompare, class Disposer>
   size_type erase_and_dispose(const KeyType& key, KeyValueCompare comp, Disposer disposer);

   //! @copydoc ::boost::intrusive::bstree::clear
   void clear();

   //! @copydoc ::boost::intrusive::bstree::clear_and_dispose
   template<class Disposer>
   void clear_and_dispose(Disposer disposer);

   #endif   //   #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED

   //! @copydoc ::boost::intrusive::bstree::count(const_reference)const
   size_type count(const_reference value) const
   {  return static_cast<size_type>(this->tree_type::find(value) == this->tree_type::cend()); }

   //! @copydoc ::boost::intrusive::bstree::count(const KeyType&,KeyValueCompare)const
   template<class KeyType, class KeyValueCompare>
   size_type count(const KeyType& key, KeyValueCompare comp) const
   {  return static_cast<size_type>(this->tree_type::find(key, comp) == this->tree_type::cend()); }

   #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED

   //! @copydoc ::boost::intrusive::bstree::lower_bound(const_reference)
   iterator lower_bound(const_reference value);

   //! @copydoc ::boost::intrusive::bstree::lower_bound(const KeyType&,KeyValueCompare)
   template<class KeyType, class KeyValueCompare>
   iterator lower_bound(const KeyType& key, KeyValueCompare comp);

   //! @copydoc ::boost::intrusive::bstree::lower_bound(const_reference)const
   const_iterator lower_bound(const_reference value) const;

   //! @copydoc ::boost::intrusive::bstree::lower_bound(const KeyType&,KeyValueCompare)const
   template<class KeyType, class KeyValueCompare>
   const_iterator lower_bound(const KeyType& key, KeyValueCompare comp) const;

   //! @copydoc ::boost::intrusive::bstree::upper_bound(const_reference)
   iterator upper_bound(const_reference value);

   //! @copydoc ::boost::intrusive::bstree::upper_bound(const KeyType&,KeyValueCompare)
   template<class KeyType, class KeyValueCompare>
   iterator upper_bound(const KeyType& key, KeyValueCompare comp);

   //! @copydoc ::boost::intrusive::bstree::upper_bound(const_reference)const
   const_iterator upper_bound(const_reference value) const;

   //! @copydoc ::boost::intrusive::bstree::upper_bound(const KeyType&,KeyValueCompare)const
   template<class KeyType, class KeyValueCompare>
   const_iterator upper_bound(const KeyType& key, KeyValueCompare comp) const;

   //! @copydoc ::boost::intrusive::bstree::find(const_reference)
   iterator find(const_reference value);

   //! @copydoc ::boost::intrusive::bstree::find(const KeyType&,KeyValueCompare)
   template<class KeyType, class KeyValueCompare>
   iterator find(const KeyType& key, KeyValueCompare comp);

   //! @copydoc ::boost::intrusive::bstree::find(const_reference)const
   const_iterator find(const_reference value) const;

   //! @copydoc ::boost::intrusive::bstree::find(const KeyType&,KeyValueCompare)const
   template<class KeyType, class KeyValueCompare>
   const_iterator find(const KeyType& key, KeyValueCompare comp) const;

   #endif   //   #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED

   //! @copydoc ::boost::intrusive::rbtree::equal_range(const_reference)
   std::pair<iterator,iterator> equal_range(const_reference value)
   {  return this->tree_type::lower_bound_range(value); }

   //! @copydoc ::boost::intrusive::rbtree::equal_range(const KeyType&,KeyValueCompare)
   template<class KeyType, class KeyValueCompare>
   std::pair<iterator,iterator> equal_range(const KeyType& key, KeyValueCompare comp)
   {  return this->tree_type::lower_bound_range(key, comp); }

   //! @copydoc ::boost::intrusive::rbtree::equal_range(const_reference)const
   std::pair<const_iterator, const_iterator>
      equal_range(const_reference value) const
   {  return this->tree_type::lower_bound_range(value); }

   //! @copydoc ::boost::intrusive::rbtree::equal_range(const KeyType&,KeyValueCompare)const
   template<class KeyType, class KeyValueCompare>
   std::pair<const_iterator, const_iterator>
      equal_range(const KeyType& key, KeyValueCompare comp) const
   {  return this->tree_type::lower_bound_range(key, comp); }

   #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED

   //! @copydoc ::boost::intrusive::bstree::bounded_range(const_reference,const_reference,bool,bool)
   std::pair<iterator,iterator> bounded_range
      (const_reference lower_value, const_reference upper_value, bool left_closed, bool right_closed);

   //! @copydoc ::boost::intrusive::bstree::bounded_range(const KeyType&,const KeyType&,KeyValueCompare,bool,bool)
   template<class KeyType, class KeyValueCompare>
   std::pair<iterator,iterator> bounded_range
      (const KeyType& lower_key, const KeyType& upper_key, KeyValueCompare comp, bool left_closed, bool right_closed);

   //! @copydoc ::boost::intrusive::bstree::bounded_range(const_reference,const_reference,bool,bool)const
   std::pair<const_iterator, const_iterator>
      bounded_range(const_reference lower_value, const_reference upper_value, bool left_closed, bool right_closed) const;

   //! @copydoc ::boost::intrusive::bstree::bounded_range(const KeyType&,const KeyType&,KeyValueCompare,bool,bool)const
   template<class KeyType, class KeyValueCompare>
   std::pair<const_iterator, const_iterator> bounded_range
         (const KeyType& lower_key, const KeyType& upper_key, KeyValueCompare comp, bool left_closed, bool right_closed) const;

   //! @copydoc ::boost::intrusive::bstree::s_iterator_to(reference)
   static iterator s_iterator_to(reference value);

   //! @copydoc ::boost::intrusive::bstree::s_iterator_to(const_reference)
   static const_iterator s_iterator_to(const_reference value);

   //! @copydoc ::boost::intrusive::bstree::iterator_to(reference)
   iterator iterator_to(reference value);

   //! @copydoc ::boost::intrusive::bstree::iterator_to(const_reference)const
   const_iterator iterator_to(const_reference value) const;

   //! @copydoc ::boost::intrusive::bstree::init_node(reference)
   static void init_node(reference value);

   //! @copydoc ::boost::intrusive::bstree::unlink_leftmost_without_rebalance
   pointer unlink_leftmost_without_rebalance();

   //! @copydoc ::boost::intrusive::bstree::replace_node
   void replace_node(iterator replace_this, reference with_this);

   //! @copydoc ::boost::intrusive::bstree::remove_node
   void remove_node(reference value);
   #endif   //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED
};

#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED)

template<class T, class ...Options>
bool operator!= (const bs_set_impl<T, Options...> &x, const bs_set_impl<T, Options...> &y);

template<class T, class ...Options>
bool operator>(const bs_set_impl<T, Options...> &x, const bs_set_impl<T, Options...> &y);

template<class T, class ...Options>
bool operator<=(const bs_set_impl<T, Options...> &x, const bs_set_impl<T, Options...> &y);

template<class T, class ...Options>
bool operator>=(const bs_set_impl<T, Options...> &x, const bs_set_impl<T, Options...> &y);

template<class T, class ...Options>
void swap(bs_set_impl<T, Options...> &x, bs_set_impl<T, Options...> &y);

#endif   //#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED)

//! Helper metafunction to define a \c bs_set that yields to the same type when the
//! same options (either explicitly or implicitly) are used.
#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
template<class T, class ...Options>
#else
template<class T, class O1 = void, class O2 = void
                , class O3 = void, class O4 = void
                , class O5 = void>
#endif
struct make_bs_set
{
   /// @cond
   typedef typename pack_options
      < bstree_defaults,
      #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
      O1, O2, O3, O4, O5
      #else
      Options...
      #endif
      >::type packed_options;

   typedef typename detail::get_value_traits
      <T, typename packed_options::proto_value_traits>::type value_traits;
   typedef typename detail::get_header_holder_type
      < value_traits, typename packed_options::header_holder_type >::type header_holder_type;

   typedef bs_set_impl
         < value_traits
         , typename packed_options::compare
         , typename packed_options::size_type
         , packed_options::constant_time_size
         , header_holder_type
         > implementation_defined;
   /// @endcond
   typedef implementation_defined type;
};

#ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED
#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
template<class T, class O1, class O2, class O3, class O4, class O5>
#else
template<class T, class ...Options>
#endif
class bs_set
   :  public make_bs_set<T,
   #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
   O1, O2, O3, O4, O5
   #else
   Options...
   #endif
   >::type
{
   typedef typename make_bs_set
      <T,
      #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
      O1, O2, O3, O4, O5
      #else
      Options...
      #endif
      >::type   Base;

   BOOST_MOVABLE_BUT_NOT_COPYABLE(bs_set)
   public:
   typedef typename Base::value_compare      value_compare;
   typedef typename Base::value_traits       value_traits;
   typedef typename Base::iterator           iterator;
   typedef typename Base::const_iterator     const_iterator;

   //Assert if passed value traits are compatible with the type
   BOOST_STATIC_ASSERT((detail::is_same<typename value_traits::value_type, T>::value));

   explicit bs_set( const value_compare &cmp = value_compare()
                  , const value_traits &v_traits = value_traits())
      :  Base(cmp, v_traits)
   {}

   template<class Iterator>
   bs_set( Iterator b, Iterator e
      , const value_compare &cmp = value_compare()
      , const value_traits &v_traits = value_traits())
      :  Base(b, e, cmp, v_traits)
   {}

   bs_set(BOOST_RV_REF(bs_set) x)
      :  Base(::boost::move(static_cast<Base&>(x)))
   {}

   bs_set& operator=(BOOST_RV_REF(bs_set) x)
   {  return static_cast<bs_set &>(this->Base::operator=(::boost::move(static_cast<Base&>(x))));  }

   static bs_set &container_from_end_iterator(iterator end_iterator)
   {  return static_cast<bs_set &>(Base::container_from_end_iterator(end_iterator));   }

   static const bs_set &container_from_end_iterator(const_iterator end_iterator)
   {  return static_cast<const bs_set &>(Base::container_from_end_iterator(end_iterator));   }

   static bs_set &container_from_iterator(iterator it)
   {  return static_cast<bs_set &>(Base::container_from_iterator(it));   }

   static const bs_set &container_from_iterator(const_iterator it)
   {  return static_cast<const bs_set &>(Base::container_from_iterator(it));   }
};

#endif

//! The class template bs_multiset is an intrusive container, that mimics most of
//! the interface of std::multiset as described in the C++ standard.
//!
//! The template parameter \c T is the type to be managed by the container.
//! The user can specify additional options and if no options are provided
//! default options are used.
//!
//! The container supports the following options:
//! \c base_hook<>/member_hook<>/value_traits<>,
//! \c constant_time_size<>, \c size_type<> and
//! \c compare<>.
#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED)
template<class T, class ...Options>
#else
template<class ValueTraits, class Compare, class SizeType, bool ConstantTimeSize, typename HeaderHolder>
#endif
class bs_multiset_impl
#ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED
   : public bstree_impl<ValueTraits, Compare, SizeType, ConstantTimeSize, RbTreeAlgorithms, HeaderHolder>
#endif
{
   /// @cond
   typedef bstree_impl<ValueTraits, Compare, SizeType, ConstantTimeSize, RbTreeAlgorithms, HeaderHolder> tree_type;

   BOOST_MOVABLE_BUT_NOT_COPYABLE(bs_multiset_impl)
   typedef tree_type implementation_defined;
   /// @endcond

   public:
   typedef typename implementation_defined::value_type               value_type;
   typedef typename implementation_defined::value_traits             value_traits;
   typedef typename implementation_defined::pointer                  pointer;
   typedef typename implementation_defined::const_pointer            const_pointer;
   typedef typename implementation_defined::reference                reference;
   typedef typename implementation_defined::const_reference          const_reference;
   typedef typename implementation_defined::difference_type          difference_type;
   typedef typename implementation_defined::size_type                size_type;
   typedef typename implementation_defined::value_compare            value_compare;
   typedef typename implementation_defined::key_compare              key_compare;
   typedef typename implementation_defined::iterator                 iterator;
   typedef typename implementation_defined::const_iterator           const_iterator;
   typedef typename implementation_defined::reverse_iterator         reverse_iterator;
   typedef typename implementation_defined::const_reverse_iterator   const_reverse_iterator;
   typedef typename implementation_defined::insert_commit_data       insert_commit_data;
   typedef typename implementation_defined::node_traits              node_traits;
   typedef typename implementation_defined::node                     node;
   typedef typename implementation_defined::node_ptr                 node_ptr;
   typedef typename implementation_defined::const_node_ptr           const_node_ptr;
   typedef typename implementation_defined::node_algorithms          node_algorithms;

   static const bool constant_time_size = tree_type::constant_time_size;

   public:
   //! @copydoc ::boost::intrusive::bstree::bstree(const value_compare &,const value_traits &)
   explicit bs_multiset_impl( const value_compare &cmp = value_compare()
                            , const value_traits &v_traits = value_traits())
      :  tree_type(cmp, v_traits)
   {}

   //! @copydoc ::boost::intrusive::bstree::bstree(bool,Iterator,Iterator,const value_compare &,const value_traits &)
   template<class Iterator>
   bs_multiset_impl( Iterator b, Iterator e
                , const value_compare &cmp = value_compare()
                , const value_traits &v_traits = value_traits())
      : tree_type(false, b, e, cmp, v_traits)
   {}

   //! @copydoc ::boost::intrusive::bstree::bstree(bstree &&)
   bs_multiset_impl(BOOST_RV_REF(bs_multiset_impl) x)
      :  tree_type(::boost::move(static_cast<tree_type&>(x)))
   {}

   //! @copydoc ::boost::intrusive::bstree::operator=(bstree &&)
   bs_multiset_impl& operator=(BOOST_RV_REF(bs_multiset_impl) x)
   {  return static_cast<bs_multiset_impl&>(tree_type::operator=(::boost::move(static_cast<tree_type&>(x)))); }

   #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED
   //! @copydoc ::boost::intrusive::bstree::~bstree()
   ~bs_multiset_impl();

   //! @copydoc ::boost::intrusive::bstree::begin()
   iterator begin();

   //! @copydoc ::boost::intrusive::bstree::begin()const
   const_iterator begin() const;

   //! @copydoc ::boost::intrusive::bstree::cbegin()const
   const_iterator cbegin() const;

   //! @copydoc ::boost::intrusive::bstree::end()
   iterator end();

   //! @copydoc ::boost::intrusive::bstree::end()const
   const_iterator end() const;

   //! @copydoc ::boost::intrusive::bstree::cend()const
   const_iterator cend() const;

   //! @copydoc ::boost::intrusive::bstree::rbegin()
   reverse_iterator rbegin();

   //! @copydoc ::boost::intrusive::bstree::rbegin()const
   const_reverse_iterator rbegin() const;

   //! @copydoc ::boost::intrusive::bstree::crbegin()const
   const_reverse_iterator crbegin() const;

   //! @copydoc ::boost::intrusive::bstree::rend()
   reverse_iterator rend();

   //! @copydoc ::boost::intrusive::bstree::rend()const
   const_reverse_iterator rend() const;

   //! @copydoc ::boost::intrusive::bstree::crend()const
   const_reverse_iterator crend() const;

   //! @copydoc ::boost::intrusive::bstree::container_from_end_iterator(iterator)
   static bs_multiset_impl &container_from_end_iterator(iterator end_iterator);

   //! @copydoc ::boost::intrusive::bstree::container_from_end_iterator(const_iterator)
   static const bs_multiset_impl &container_from_end_iterator(const_iterator end_iterator);

   //! @copydoc ::boost::intrusive::bstree::container_from_iterator(iterator)
   static bs_multiset_impl &container_from_iterator(iterator it);

   //! @copydoc ::boost::intrusive::bstree::container_from_iterator(const_iterator)
   static const bs_multiset_impl &container_from_iterator(const_iterator it);

   //! @copydoc ::boost::intrusive::bstree::key_comp()const
   key_compare key_comp() const;

   //! @copydoc ::boost::intrusive::bstree::value_comp()const
   value_compare value_comp() const;

   //! @copydoc ::boost::intrusive::bstree::empty()const
   bool empty() const;

   //! @copydoc ::boost::intrusive::bstree::size()const
   size_type size() const;

   //! @copydoc ::boost::intrusive::bstree::swap
   void swap(bs_multiset_impl& other);

   //! @copydoc ::boost::intrusive::bstree::clone_from
   template <class Cloner, class Disposer>
   void clone_from(const bs_multiset_impl &src, Cloner cloner, Disposer disposer);

   #endif   //#ifdef BOOST_iNTRUSIVE_DOXYGEN_INVOKED

   //! @copydoc ::boost::intrusive::bstree::insert_equal(reference)
   iterator insert(reference value)
   {  return tree_type::insert_equal(value);  }

   //! @copydoc ::boost::intrusive::bstree::insert_equal(const_iterator,reference)
   iterator insert(const_iterator hint, reference value)
   {  return tree_type::insert_equal(hint, value);  }

   //! @copydoc ::boost::intrusive::bstree::insert_equal(Iterator,Iterator)
   template<class Iterator>
   void insert(Iterator b, Iterator e)
   {  tree_type::insert_equal(b, e);  }

   #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED
   //! @copydoc ::boost::intrusive::bstree::insert_before
   iterator insert_before(const_iterator pos, reference value);

   //! @copydoc ::boost::intrusive::bstree::push_back
   void push_back(reference value);

   //! @copydoc ::boost::intrusive::bstree::push_front
   void push_front(reference value);

   //! @copydoc ::boost::intrusive::bstree::erase(const_iterator)
   iterator erase(const_iterator i);

   //! @copydoc ::boost::intrusive::bstree::erase(const_iterator,const_iterator)
   iterator erase(const_iterator b, const_iterator e);

   //! @copydoc ::boost::intrusive::bstree::erase(const_reference)
   size_type erase(const_reference value);

   //! @copydoc ::boost::intrusive::bstree::erase(const KeyType&,KeyValueCompare)
   template<class KeyType, class KeyValueCompare>
   size_type erase(const KeyType& key, KeyValueCompare comp);

   //! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const_iterator,Disposer)
   template<class Disposer>
   iterator erase_and_dispose(const_iterator i, Disposer disposer);

   //! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const_iterator,const_iterator,Disposer)
   template<class Disposer>
   iterator erase_and_dispose(const_iterator b, const_iterator e, Disposer disposer);

   //! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const_reference, Disposer)
   template<class Disposer>
   size_type erase_and_dispose(const_reference value, Disposer disposer);

   //! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const KeyType&,KeyValueCompare,Disposer)
   template<class KeyType, class KeyValueCompare, class Disposer>
   size_type erase_and_dispose(const KeyType& key, KeyValueCompare comp, Disposer disposer);

   //! @copydoc ::boost::intrusive::bstree::clear
   void clear();

   //! @copydoc ::boost::intrusive::bstree::clear_and_dispose
   template<class Disposer>
   void clear_and_dispose(Disposer disposer);

   //! @copydoc ::boost::intrusive::bstree::count(const_reference)const
   size_type count(const_reference value) const;

   //! @copydoc ::boost::intrusive::bstree::count(const KeyType&,KeyValueCompare)const
   template<class KeyType, class KeyValueCompare>
   size_type count(const KeyType& key, KeyValueCompare comp) const;

   //! @copydoc ::boost::intrusive::bstree::lower_bound(const_reference)
   iterator lower_bound(const_reference value);

   //! @copydoc ::boost::intrusive::bstree::lower_bound(const KeyType&,KeyValueCompare)
   template<class KeyType, class KeyValueCompare>
   iterator lower_bound(const KeyType& key, KeyValueCompare comp);

   //! @copydoc ::boost::intrusive::bstree::lower_bound(const_reference)const
   const_iterator lower_bound(const_reference value) const;

   //! @copydoc ::boost::intrusive::bstree::lower_bound(const KeyType&,KeyValueCompare)const
   template<class KeyType, class KeyValueCompare>
   const_iterator lower_bound(const KeyType& key, KeyValueCompare comp) const;

   //! @copydoc ::boost::intrusive::bstree::upper_bound(const_reference)
   iterator upper_bound(const_reference value);

   //! @copydoc ::boost::intrusive::bstree::upper_bound(const KeyType&,KeyValueCompare)
   template<class KeyType, class KeyValueCompare>
   iterator upper_bound(const KeyType& key, KeyValueCompare comp);

   //! @copydoc ::boost::intrusive::bstree::upper_bound(const_reference)const
   const_iterator upper_bound(const_reference value) const;

   //! @copydoc ::boost::intrusive::bstree::upper_bound(const KeyType&,KeyValueCompare)const
   template<class KeyType, class KeyValueCompare>
   const_iterator upper_bound(const KeyType& key, KeyValueCompare comp) const;

   //! @copydoc ::boost::intrusive::bstree::find(const_reference)
   iterator find(const_reference value);

   //! @copydoc ::boost::intrusive::bstree::find(const KeyType&,KeyValueCompare)
   template<class KeyType, class KeyValueCompare>
   iterator find(const KeyType& key, KeyValueCompare comp);

   //! @copydoc ::boost::intrusive::bstree::find(const_reference)const
   const_iterator find(const_reference value) const;

   //! @copydoc ::boost::intrusive::bstree::find(const KeyType&,KeyValueCompare)const
   template<class KeyType, class KeyValueCompare>
   const_iterator find(const KeyType& key, KeyValueCompare comp) const;

   //! @copydoc ::boost::intrusive::bstree::equal_range(const_reference)
   std::pair<iterator,iterator> equal_range(const_reference value);

   //! @copydoc ::boost::intrusive::bstree::equal_range(const KeyType&,KeyValueCompare)
   template<class KeyType, class KeyValueCompare>
   std::pair<iterator,iterator> equal_range(const KeyType& key, KeyValueCompare comp);

   //! @copydoc ::boost::intrusive::bstree::equal_range(const_reference)const
   std::pair<const_iterator, const_iterator>
      equal_range(const_reference value) const;

   //! @copydoc ::boost::intrusive::bstree::equal_range(const KeyType&,KeyValueCompare)const
   template<class KeyType, class KeyValueCompare>
   std::pair<const_iterator, const_iterator>
      equal_range(const KeyType& key, KeyValueCompare comp) const;

   //! @copydoc ::boost::intrusive::bstree::bounded_range(const_reference,const_reference,bool,bool)
   std::pair<iterator,iterator> bounded_range
      (const_reference lower_value, const_reference upper_value, bool left_closed, bool right_closed);

   //! @copydoc ::boost::intrusive::bstree::bounded_range(const KeyType&,const KeyType&,KeyValueCompare,bool,bool)
   template<class KeyType, class KeyValueCompare>
   std::pair<iterator,iterator> bounded_range
      (const KeyType& lower_key, const KeyType& upper_key, KeyValueCompare comp, bool left_closed, bool right_closed);

   //! @copydoc ::boost::intrusive::bstree::bounded_range(const_reference,const_reference,bool,bool)const
   std::pair<const_iterator, const_iterator>
      bounded_range(const_reference lower_value, const_reference upper_value, bool left_closed, bool right_closed) const;

   //! @copydoc ::boost::intrusive::bstree::bounded_range(const KeyType&,const KeyType&,KeyValueCompare,bool,bool)const
   template<class KeyType, class KeyValueCompare>
   std::pair<const_iterator, const_iterator> bounded_range
         (const KeyType& lower_key, const KeyType& upper_key, KeyValueCompare comp, bool left_closed, bool right_closed) const;

   //! @copydoc ::boost::intrusive::bstree::s_iterator_to(reference)
   static iterator s_iterator_to(reference value);

   //! @copydoc ::boost::intrusive::bstree::s_iterator_to(const_reference)
   static const_iterator s_iterator_to(const_reference value);

   //! @copydoc ::boost::intrusive::bstree::iterator_to(reference)
   iterator iterator_to(reference value);

   //! @copydoc ::boost::intrusive::bstree::iterator_to(const_reference)const
   const_iterator iterator_to(const_reference value) const;

   //! @copydoc ::boost::intrusive::bstree::init_node(reference)
   static void init_node(reference value);

   //! @copydoc ::boost::intrusive::bstree::unlink_leftmost_without_rebalance
   pointer unlink_leftmost_without_rebalance();

   //! @copydoc ::boost::intrusive::bstree::replace_node
   void replace_node(iterator replace_this, reference with_this);

   //! @copydoc ::boost::intrusive::bstree::remove_node
   void remove_node(reference value);
   #endif   //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED
};

#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED)

template<class T, class ...Options>
bool operator!= (const bs_multiset_impl<T, Options...> &x, const bs_multiset_impl<T, Options...> &y);

template<class T, class ...Options>
bool operator>(const bs_multiset_impl<T, Options...> &x, const bs_multiset_impl<T, Options...> &y);

template<class T, class ...Options>
bool operator<=(const bs_multiset_impl<T, Options...> &x, const bs_multiset_impl<T, Options...> &y);

template<class T, class ...Options>
bool operator>=(const bs_multiset_impl<T, Options...> &x, const bs_multiset_impl<T, Options...> &y);

template<class T, class ...Options>
void swap(bs_multiset_impl<T, Options...> &x, bs_multiset_impl<T, Options...> &y);

#endif   //#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED)

//! Helper metafunction to define a \c bs_multiset that yields to the same type when the
//! same options (either explicitly or implicitly) are used.
#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
template<class T, class ...Options>
#else
template<class T, class O1 = void, class O2 = void
                , class O3 = void, class O4 = void
                , class O5 = void>
#endif
struct make_bs_multiset
{
   /// @cond
   typedef typename pack_options
      < bstree_defaults,
      #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
      O1, O2, O3, O4, O5
      #else
      Options...
      #endif
      >::type packed_options;

   typedef typename detail::get_value_traits
      <T, typename packed_options::proto_value_traits>::type value_traits;
   typedef typename detail::get_header_holder_type
      < value_traits, typename packed_options::header_holder_type >::type header_holder_type;

   typedef bs_multiset_impl
         < value_traits
         , typename packed_options::compare
         , typename packed_options::size_type
         , packed_options::constant_time_size
         , header_holder_type
         > implementation_defined;
   /// @endcond
   typedef implementation_defined type;
};

#ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED

#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
template<class T, class O1, class O2, class O3, class O4, class O5>
#else
template<class T, class ...Options>
#endif
class bs_multiset
   :  public make_bs_multiset<T,
      #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
      O1, O2, O3, O4, O5
      #else
      Options...
      #endif
      >::type
{
   typedef typename make_bs_multiset<T,
      #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
      O1, O2, O3, O4, O5
      #else
      Options...
      #endif
      >::type   Base;

   BOOST_MOVABLE_BUT_NOT_COPYABLE(bs_multiset)

   public:
   typedef typename Base::value_compare      value_compare;
   typedef typename Base::value_traits       value_traits;
   typedef typename Base::iterator           iterator;
   typedef typename Base::const_iterator     const_iterator;

   //Assert if passed value traits are compatible with the type
   BOOST_STATIC_ASSERT((detail::is_same<typename value_traits::value_type, T>::value));

   explicit bs_multiset( const value_compare &cmp = value_compare()
                       , const value_traits &v_traits = value_traits())
      :  Base(cmp, v_traits)
   {}

   template<class Iterator>
   bs_multiset( Iterator b, Iterator e
           , const value_compare &cmp = value_compare()
           , const value_traits &v_traits = value_traits())
      :  Base(b, e, cmp, v_traits)
   {}

   bs_multiset(BOOST_RV_REF(bs_multiset) x)
      :  Base(::boost::move(static_cast<Base&>(x)))
   {}

   bs_multiset& operator=(BOOST_RV_REF(bs_multiset) x)
   {  return static_cast<bs_multiset &>(this->Base::operator=(::boost::move(static_cast<Base&>(x))));  }

   static bs_multiset &container_from_end_iterator(iterator end_iterator)
   {  return static_cast<bs_multiset &>(Base::container_from_end_iterator(end_iterator));   }

   static const bs_multiset &container_from_end_iterator(const_iterator end_iterator)
   {  return static_cast<const bs_multiset &>(Base::container_from_end_iterator(end_iterator));   }

   static bs_multiset &container_from_iterator(iterator it)
   {  return static_cast<bs_multiset &>(Base::container_from_iterator(it));   }

   static const bs_multiset &container_from_iterator(const_iterator it)
   {  return static_cast<const bs_multiset &>(Base::container_from_iterator(it));   }
};

#endif

} //namespace intrusive
} //namespace boost

#include <boost/intrusive/detail/config_end.hpp>

#endif //BOOST_INTRUSIVE_BS_SET_HPP

max_stars_repo_name: fduffy/QuantLibAdjoint

max_issues_repo_name: fduffy/QuantLibAdjoint

max_forks_repo_name: fduffy/QuantLibAdjoint


text:
/*************************************************************************
 * Copyright (C) 2017-2019 Barcelona Supercomputing Center               *
 *                         Centro Nacional de Supercomputacion           *
 * All rights reserved.                                                  *
 *                                                                       *
 * This file is part of NORNS, a service that allows other programs to   *
 * start, track and manage asynchronous transfers of data resources      *
 * between different storage backends.                                   *
 *                                                                       *
 * See AUTHORS file in the top level directory for information regarding *
 * developers and contributors.                                          *
 *                                                                       *
 * This software was developed as part of the EC H2020 funded project    *
 * NEXTGenIO (Project ID: 671951).                                       *
 *     www.nextgenio.eu                                                  *
 *                                                                       *
 * Permission is hereby granted, free of charge, to any person obtaining *
 * a copy of this software and associated documentation files (the       *
 * "Software"), to deal in the Software without restriction, including   *
 * without limitation the rights to use, copy, modify, merge, publish,   *
 * distribute, sublicense, and/or sell copies of the Software, and to    *
 * permit persons to whom the Software is furnished to do so, subject to *
 * the following conditions:                                             *
 *                                                                       *
 * The above copyright notice and this permission notice shall be        *
 * included in all copies or substantial portions of the Software.       *
 *                                                                       *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       *
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    *
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND                 *
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS   *
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN    *
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN     *
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE      *
 * SOFTWARE.                                                             *
 *************************************************************************/

#ifndef __API_SESSION_HPP__
#define __API_SESSION_HPP__

#include <boost/asio.hpp>
#include <boost/filesystem.hpp>

#include "common.hpp"
#include "auth/process-credentials.hpp"

namespace ba = boost::asio;
namespace bfs = boost::filesystem;

namespace norns {
namespace api {

// forward declarations
template <typename Message> class local_endpoint;
template <typename Message> class remote_endpoint;

/* helper class for managing communication sessions with a client */
template <typename Socket, typename Message>
class session : public std::enable_shared_from_this<session<Socket, Message>> {

    friend class local_endpoint<Message>;
    friend class remote_endpoint<Message>;

    using Dispatcher = dispatch_table<
        typename Message::key_type,
        typename Message::key_hash_type,
        std::unique_ptr<typename Message::response_type>,
        std::unique_ptr<typename Message::request_type>
            >;

    using Input = std::unique_ptr<typename Message::request_type>;
    using Output = std::unique_ptr<typename Message::response_type>;

public:
    session(Socket&& socket,
            std::shared_ptr<Dispatcher> dispatcher)
        : m_socket(std::move(socket)),
          m_dispatcher(dispatcher) {}

    ~session() {
//        std::cerr << "session dying\n";
    }

    void start() {
        do_read_request();
    }

private:
    void do_read_request() {

        auto self(std::enable_shared_from_this<
                session<Socket, Message>>::shared_from_this());

        std::size_t header_length = m_message.expected_length(Message::header);

        // read the request header and use the information provided in it
        // to read the request body
        ba::async_read(m_socket,
                ba::buffer(m_message.buffer(Message::header), header_length),
                [this, self](boost::system::error_code ec, std::size_t length) {

                    if(!ec && m_message.decode_header(length)) {
                        //FIXME: check what happens if the caller never
                        //sends a body... are we leaking?
                        do_read_request_body();
                    }
                });
    }

    void do_read_request_body() {

        auto self(std::enable_shared_from_this<
                session<Socket, Message>>::shared_from_this());

        std::size_t body_length = m_message.expected_length(Message::body);

        if(body_length != 0) {
            ba::async_read(m_socket,
                    ba::buffer(m_message.buffer(Message::body), body_length),
                    [this, self](boost::system::error_code ec, std::size_t length) {

                        if(!ec) {
                            Input req = m_message.decode_body(length);

                            // if credentials were not provided in the requests payload,
                            // the request probably originated locally. In that case, we
                            // try to get the credentials from the local calling process
                            // from the connection socket. If this also fails,
                            // req->credentials() is set to boost::none, and it becomes
                            // the invoked handler's responsibility to validate the request
                            if(!req->credentials()) {
                                req->set_credentials(
                                        auth::credentials::fetch(m_socket));
                            }

                            Output resp = m_dispatcher->invoke(
                                    req->type(), std::move(req));

                            assert(resp != nullptr);

                            m_message.clear();

                            if(m_message.encode_response(std::move(resp))) {
                                do_write_response();
                            }

                            m_socket.shutdown(ba::ip::tcp::socket::shutdown_both, ec);
                        }
                    });
        }
    }

    void do_write_response() {

        std::vector<ba::const_buffer> buffers;
        buffers.push_back(ba::buffer(m_message.buffer(Message::header)));
        buffers.push_back(ba::buffer(m_message.buffer(Message::body)));

        //Message::print_hex(m_message.buffer(Message::header));
        //Message::print_hex(m_message.buffer(Message::body));

        auto self(std::enable_shared_from_this<
                session<Socket, Message>>::shared_from_this());

        ba::async_write(m_socket, buffers,
            [this, self](boost::system::error_code ec, std::size_t /*length*/){

//                std::cerr << "Writing done!\n";

                if(!ec){
                    //do_read_request();
                }
            });
    }

    Socket m_socket;
    Message                              m_message;
    std::shared_ptr<Dispatcher> m_dispatcher;
};

} // namespace api
} // namespace norns

#endif /* __API_SESSION_HPP__ */

ext: hpp

max_stars_repo_name: bsc-ssrg/NORNS

max_issues_repo_name: bsc-ssrg/NORNS

max_forks_repo_name: bsc-ssrg/NORNS


text:
/*
   Copyright 2020 - 2021 The Silkworm Authors

   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.
*/

#ifndef SILKWORM_CONCURRENCY_WORKER_HPP_
#define SILKWORM_CONCURRENCY_WORKER_HPP_

#include <atomic>
#include <condition_variable>
#include <iostream>
#include <thread>

#include <silkworm/common/signal_handler.hpp>
#include <boost/signals2/signal.hpp>

namespace silkworm {

// If you only need stoppability, use ActiveComponent instead.
class Worker {
  public:

    enum class State { kStopped, kStarting, kStarted, kKickWaiting, kStopping };

    Worker() : name_{"worker"}{};
    explicit Worker(std::string& name) : name_{name}{};
    explicit Worker(std::string&& name) : name_{std::move(name)}{};

    /* Not movable nor copyable */
    Worker(Worker const&) = delete;
    Worker& operator=(Worker const&) = delete;

    virtual ~Worker();

    void start(bool wait = true);  // Start worker thread (by default waits for status)
    void stop(bool wait = false);  // Stops worker thread (optionally wait for complete stop)
    void kick();                   // Kicks worker thread if waiting

    //! \brief Whether this worker/thread has received a stop request
    bool is_stopping() const { return state_.load() == State::kStopping; }

    //! \brief Retrieves current state of thread
    State get_state() { return state_.load(); }

    //! \brief Whether this worker/thread has encountered an exception
    bool has_exception() const { return exception_ptr_ != nullptr; }

    //! \brief Returns the message of captured exception (if any)
    std::string what();

    //! \brief Rethrows captured exception (if any)
    void rethrow();

    //! \brief Signals connected handlers the underlying thread is about to start
    boost::signals2::signal<void(Worker* sender)> signal_worker_started;

    //! \brief Signals connected handlers the underlying thread is terminated
    boost::signals2::signal<void(Worker* sender)> signal_worker_stopped;

  protected:
    /**
     * @brief Puts the underlying thread in non-busy wait for a kick
     * to waken up and do work.
     * Returns True if the kick has been received and should go ahead
     * otherwise False (i.e. the thread has been asked to stop)
     *
     * @param [in] timeout: Timeout for conditional variable wait (milliseconds). Defaults to 100 ms
     */
    bool wait_for_kick(uint32_t timeout_milliseconds = 100);  // Puts a thread in non-busy wait for data to process
    std::atomic_bool kicked_{false};                          // Whether the kick has been received
    std::condition_variable kicked_cv_{};                     // Condition variable to wait for kick
    std::mutex kick_mtx_{};                                   // Mutex for conditional wait of kick
    std::string name_;

  private:
    std::atomic<State> state_{State::kStopped};
    std::unique_ptr<std::thread> thread_{nullptr};
    std::exception_ptr exception_ptr_{nullptr};
    virtual void work() = 0;  // Derived classes must override
};

}  // namespace silkworm

#endif  // SILKWORM_CONCURRENCY_WORKER_HPP_


text:
// Copyright (c) 2013-2021 niXman (github dotty nixman doggy pm dotty me)
// All rights reserved.
//
// This file is part of EASYNET(https://github.com/niXman/easynet) project.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   Redistributions of source code must retain the above copyright notice, this
//   list of conditions and the following disclaimer.
//
//   Redistributions in binary form must reproduce the above copyright notice, this
//   list of conditions and the following disclaimer in the documentation and/or
//   other materials provided with the distribution.
//
//   Neither the name of the {organization} nor the names of its
//   contributors may be used to endorse or promote products derived from
//   this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <easynet/timer.hpp>

#include <boost/asio/io_context.hpp>

#include <iostream>

/***************************************************************************/

struct timer_object: std::enable_shared_from_this<timer_object> {
    timer_object(boost::asio::io_context &ios)
        :m_timer{ios}
    {}

    void start() {
        m_timer.start(
             1000
            ,[this]
             (const easynet::error_code &ec, easynet::impl_holder holder)
             { on_timeout_0(ec, std::move(holder)); }
            ,shared_from_this()
        );
    }

    void on_timeout_0(const easynet::error_code &ec, easynet::impl_holder holder) {
        std::cout << "on_timeout_0(): ec=" << ec << std::endl;

        m_timer.start(1000, this, &timer_object::on_timeout_1, std::move(holder));
    }
    void on_timeout_1(const easynet::error_code &ec, easynet::impl_holder) {
        std::cout << "on_timeout_1(): ec=" << ec << std::endl;

    }

    easynet::timer m_timer;
};

/***************************************************************************/

int main(int, char**) {
    try {
        boost::asio::io_context ios;

        {
            auto timer = std::make_shared<timer_object>(ios);
            timer->start();
        }

        ios.run();
    } catch (const std::exception &ex) {
        std::cout << "[exception]: " << ex.what() << std::endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

/***************************************************************************/

ext: cpp

max_stars_repo_name: niXman/easynet

max_issues_repo_name: niXman/easynet

max_forks_repo_name: niXman/easynet


text:
//
// Copyright (c) 2015, Deutsches Forschungszentrum für Künstliche Intelligenz GmbH.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
//   list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//

#ifndef __ENVIRE_CORE_SPATIAL_ITEM__
#define __ENVIRE_CORE_SPATIAL_ITEM__

#include <envire_core/items/Item.hpp>
#include <envire_core/items/BoundingVolume.hpp>
#include <boost/shared_ptr.hpp>
#include <Eigen/Geometry>

namespace envire { namespace core
{

    /**@class SpatialItem
    *
    * SpatialItem class
    */
    template<class _ItemData>
    class SpatialItem : public Item<_ItemData>
    {

    public:
        typedef boost::shared_ptr< SpatialItem<_ItemData> > Ptr;

    protected:
        boost::shared_ptr<BoundingVolume> boundary;

    public:

        SpatialItem() : Item<_ItemData>()
        {

        };

        virtual ~SpatialItem() {}

        void setBoundary(const boost::shared_ptr<BoundingVolume>& boundary) {this->boundary = boundary;}

        boost::shared_ptr<BoundingVolume> getBoundary() {return boundary;}
        const boost::shared_ptr<BoundingVolume>& getBoundary() const {return boundary;}

        void extendBoundary(const Eigen::Vector3d& point)
        {
            checkBoundingVolume();
            boundary->extend(point);
        }

        template<typename _Data>
        void extendBoundary(const SpatialItem<_Data>& spatial_item)
        {
            checkBoundingVolume();
            boundary->extend(spatial_item.getBoundary());
        }

        template<typename _Data>
        bool intersects(const SpatialItem<_Data>& spatial_item) const
        {
            checkBoundingVolume();
            return boundary->intersects(spatial_item.getBoundary());
        }

        template<typename _Data>
        boost::shared_ptr<BoundingVolume> intersection(const SpatialItem<_Data>& spatial_item) const
        {
            checkBoundingVolume();
            return boundary->intersection(spatial_item.getBoundary());
        }

        bool contains(const Eigen::Vector3d& point) const
        {
            checkBoundingVolume();
            return boundary->contains(point);
        }

        template<typename _Data>
        bool contains(const SpatialItem<_Data>& spatial_item) const
        {
            checkBoundingVolume();
            return boundary->contains(spatial_item.getBoundary());
        }

        double exteriorDistance(const Eigen::Vector3d& point) const
        {
            checkBoundingVolume();
            return boundary->exteriorDistance(point);
        }

        template<typename _Data>
        double exteriorDistance(const SpatialItem<_Data>& spatial_item) const
        {
            checkBoundingVolume();
            return boundary->exteriorDistance(spatial_item.getBoundary());
        }

        Eigen::Vector3d centerOfBoundary() const
        {
            checkBoundingVolume();
            return boundary->center();
        }

    protected:
        void checkBoundingVolume() const
        {
            if(boundary.get() == NULL)
                throw std::runtime_error("BoundingVolume is not available!");
        }

    };

}}
#endif


text:
/**
 * grammar_test.hpp
 *
 *  Created on: 12 авг. 2015 г.
 *      Author: zmij
 */

#ifndef HTTP_GRAMMAR_PARSE_TEST_HPP_
#define HTTP_GRAMMAR_PARSE_TEST_HPP_

#include <gtest/gtest.h>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/support_istream_iterator.hpp>
#include <boost/spirit/include/support_multi_pass.hpp>

template < template<typename> class Grammar >
class GrammarTest : public ::testing::TestWithParam< std::string > {
protected:
	typedef std::string::const_iterator string_iterator;
	typedef Grammar< string_iterator > grammar_type;

	typedef std::istreambuf_iterator<char> istreambuf_iterator;
	typedef boost::spirit::multi_pass< istreambuf_iterator > stream_iterator;
	typedef Grammar< stream_iterator > stream_grammar_type;
	grammar_type			parser;
	stream_grammar_type		stream_parser;
};

template< template<typename> class Grammar, typename Result >
class GrammarParseTest : public ::testing::TestWithParam< std::pair< std::string, Result >> {
protected:
	typedef std::string::const_iterator string_iterator;
	typedef Grammar< string_iterator > grammar_type;

	typedef std::istreambuf_iterator<char> istreambuf_iterator;
	typedef boost::spirit::multi_pass< istreambuf_iterator > stream_iterator;
	typedef Grammar< stream_iterator > stream_grammar_type;
	grammar_type			parser;
	stream_grammar_type		stream_parser;
public:
	typedef Result result_type;
	typedef std::pair< std::string, result_type > param_type;
	static param_type
	make_test_data(std::string const& input, result_type const& expect)
	{
		return std::make_pair(input, expect);
	}
};

#define GRAMMAR_TEST(grammar_name, test_name, valid_generator, invalid_generator) \
typedef GrammarTest< grammar_name > Valid##test_name; \
typedef GrammarTest< grammar_name > Invalid##test_name; \
TEST_P(Valid##test_name, ValidInput) \
{ \
	namespace qi = boost::spirit::qi; \
	std::string input = GetParam(); \
	string_iterator first = input.begin(); \
	string_iterator last = input.end(); \
	EXPECT_TRUE(qi::parse(first, last, parser)); \
	EXPECT_EQ(last, first); \
} \
TEST_P(Valid##test_name, ValidStreamInput) \
{ \
	namespace qi = boost::spirit::qi; \
	std::string input = GetParam(); \
	std::istringstream is(input); \
	stream_iterator in = stream_iterator(istreambuf_iterator(is)); \
	stream_iterator eos = stream_iterator(istreambuf_iterator()); \
	EXPECT_TRUE(qi::parse(in, eos, stream_parser)); \
} \
INSTANTIATE_TEST_CASE_P(ParserTest, Valid##test_name, valid_generator); \
TEST_P(Invalid##test_name, InvalidInput) \
{ \
	namespace qi = boost::spirit::qi; \
	std::string input = GetParam(); \
	std::string::const_iterator first = input.begin(); \
	std::string::const_iterator last = input.end(); \
	EXPECT_FALSE(qi::parse(first, last, parser) && first == last); \
} \
INSTANTIATE_TEST_CASE_P(ParserTest, Invalid##test_name, invalid_generator)

#define GRAMMAR_PARSE_TEST(grammar_name, test_name, result_type, generator) \
typedef GrammarParseTest<grammar_name, result_type> Parse##test_name; \
TEST_P(Parse##test_name, TestParse) \
{ \
	namespace qi = boost::spirit::qi;\
	ParamType param = GetParam(); \
	result_type res; \
	string_iterator f = param.first.begin(); \
	string_iterator l = param.first.end(); \
	EXPECT_TRUE(qi::parse(f, l, parser, res)); \
	EXPECT_EQ(l, f); \
	EXPECT_EQ(param.second, res); \
} \
TEST_P(Parse##test_name, TestStreamParse) \
{ \
	namespace qi = boost::spirit::qi; \
	ParamType param = GetParam(); \
	result_type res; \
	std::istringstream is(param.first); \
	stream_iterator in = stream_iterator(istreambuf_iterator(is)); \
	stream_iterator eos = stream_iterator(istreambuf_iterator()); \
	EXPECT_TRUE(qi::parse(in, eos, stream_parser, res)); \
	EXPECT_EQ(param.second, res); \
} \
INSTANTIATE_TEST_CASE_P(ParserTest, Parse##test_name, generator)

/*
TEST_P(Valid##test_name, ValidStreambufInput) \
{ \
	namespace qi = boost::spirit::qi; \
	namespace spirit = boost::spirit; \
	std::string input = GetParam(); \
	std::istringstream is(input); \
	streambuf_multipass_iterator f = \
		spirit::make_default_multi_pass(streambuf_base_iterator(is)) \
	streambuf_multipass_iterator l = \
		spirit::make_default_multi_pass(streambuf_base_iterator()) \
	EXPECT_TRUE(qi::parse(f, l, streambuf_parser)); \
} \
 */

#endif /* HTTP_GRAMMAR_PARSE_TEST_HPP_ */

max_stars_repo_name: zmij/wire

max_issues_repo_name: zmij/wire

max_forks_repo_name: zmij/wire


text:
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <splineread.hh>
#include <TF1.h>
#include <TGraph.h>

splineread::splineread(std::string xmlfilename)
{
    boost::property_tree::ptree pt;
    boost::property_tree::xml_parser::read_xml(xmlfilename, pt);
    const auto genie_xsec_spline_list = pt.get_child("genie_xsec_spline_list");
    version = genie_xsec_spline_list.get<std::string>("<xmlattr>.version");
    uselog = genie_xsec_spline_list.get<bool>("<xmlattr>.uselog");
    const auto genie_tune = genie_xsec_spline_list.get_child("genie_tune");
    genie_tune_name = genie_tune.get<std::string>("<xmlattr>.name");
    for (const auto &spline : genie_tune)
    {
        if (spline.first == std::string("spline"))
        {
            const auto spline_name = spline.second.get<std::string>("<xmlattr>.name");
            namelist.push_back(spline_name);
            const auto spline_nknots = spline.second.get<double>("<xmlattr>.nknots");
            // next version of CERN ROOT will provide TGraph::AddPoint(), in that case
            // we could emit those std::vector containers.
            std::vector<double> Elist, xsec_list;
            Elist.reserve(spline_nknots);
            xsec_list.reserve(spline_nknots);
            for (const auto &knot : spline.second)
            {
                if (knot.first == std::string("knot"))
                {
                    Elist.push_back(knot.second.get<double>("E"));
                    xsec_list.push_back(knot.second.get<double>("xsec"));
                }
            }
            TGraph gh(spline_nknots, &Elist[0], &xsec_list[0]);
            // TGraph::Eval can sometimes used to do envaluing, while
            // TF1 can do more things, initialize a TF1 instance here
            // by lambda, TGraph instance is copied in. Life cycle is
            // managed by TF1. Hope TF1 won't introduce memory leaks.
            splinelist.insert({spline_name, new TF1(
                                                spline_name.c_str(),
                                                [gh](double *x, double *) {
                                                    return gh.Eval(x[0]);
                                                },
                                                0, 1000, 0)});
        }
    }
}

splineread::splineread(const splineread &rhs) : version(rhs.version),
                                          uselog(rhs.uselog),
                                          genie_tune_name(rhs.genie_tune_name),
                                          namelist(rhs.namelist)
{
    for (const auto &i : rhs.splinelist)
    {
        splinelist[i.first] = (TF1 *)i.second->Clone();
    }
}

splineread::splineread(splineread &&rhs) : version(rhs.version),
                                           uselog(rhs.uselog),
                                           genie_tune_name(rhs.genie_tune_name),
                                           namelist(rhs.namelist)
{
    splinelist = rhs.splinelist;
    rhs.splinelist.clear();
}

splineread::~splineread()
{
    for (const auto &i : splinelist)
    {
        delete i.second;
    }
}

TF1 *splineread::get_spline(const std::string splinename) const
{
    auto f = splinelist.find(splinename);
    if (f == splinelist.end())
    {
        return nullptr;
    }
    else
    {
        return f->second;
    }
}

ext: cc


text:
//==================================================================================================
/*!

  Copyright 2015 NumScale SAS
  Copyright 2015 J.T. Lapreste

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#include <boost/simd/function/scalar/rem_pio2_straight.hpp>
#include <simd_test.hpp>
#include <boost/simd/constant/inf.hpp>
#include <boost/simd/constant/minf.hpp>
#include <boost/simd/constant/nan.hpp>
#include <boost/simd/constant/one.hpp>
#include <boost/simd/constant/mone.hpp>
#include <boost/simd/constant/zero.hpp>
#include <boost/simd/constant/mzero.hpp>
#include <boost/simd/constant/pio_4.hpp>
#include <boost/simd/constant/pio_2.hpp>

STF_CASE_TPL (" rem_pio2_straight",  STF_IEEE_TYPES)
{
  namespace bs = boost::simd;
  namespace bd = boost::dispatch;

  using bs::rem_pio2_straight;
  using iT = bd::as_integer_t<T>;
  using r_t = decltype(rem_pio2_straight(T()));

  STF_EXPR_IS( (rem_pio2_straight(T()))
                  , (std::pair<iT,T>)
                  );

  {
    T r1;
    STF_EQUAL( rem_pio2_straight(bs::Pio_2<T>(), r1), bs::One<iT>());
    STF_ULP_EQUAL( r1, bs::Zero<T>(), 0.5);
    STF_EQUAL( rem_pio2_straight(bs::Pio_4<T>(), r1), bs::One<iT>());
    STF_ULP_EQUAL( r1, -bs::Pio_4<T>(), 0.5);
  }
  {
    r_t res = rem_pio2_straight(bs::Pio_4<T>());
    STF_ULP_EQUAL( res.first, bs::One<iT>(), 0.5);
    STF_ULP_EQUAL( res.second, -bs::Pio_4<T>(), 0.5);
  }
  {
    r_t res = rem_pio2_straight(bs::Zero<T>());
    STF_ULP_EQUAL( res.first, bs::One<iT>(), 0.5);
    STF_ULP_EQUAL( res.second, -bs::Pio_2<T>(), 0.5);
  }

}


text:
/*=============================================================================
    Copyright (c) 2001-2011 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)
==============================================================================*/
#if !defined(FUSION_CONVERT_ITERATOR_05062005_1218)
#define FUSION_CONVERT_ITERATOR_05062005_1218

#include <boost/fusion/support/config.hpp>
#include <boost/fusion/support/is_iterator.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/if.hpp>

namespace boost {
namespace fusion {
template <typename Iterator> struct mpl_iterator; // forward declaration

//  Test T. If it is a fusion iterator, return a reference to it.
//  else, assume it is an mpl iterator.

template <typename T> struct convert_iterator {
  typedef
      typename mpl::if_<is_fusion_iterator<T>, T, mpl_iterator<T>>::type type;

  BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED static T const &call(T const &x,
                                                                mpl::true_) {
    return x;
  }

  BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED static mpl_iterator<T>
  call(T const & /*x*/, mpl::false_) {
    return mpl_iterator<T>();
  }

  BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED static
      typename mpl::if_<is_fusion_iterator<T>, T const &, mpl_iterator<T>>::type
      call(T const &x) {
    return call(x, is_fusion_iterator<T>());
  }
};
} // namespace fusion
} // namespace boost

#endif

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


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

//  Copyright Pavol Droba 2002-2003. Use, modification and
//  distribution is subject to 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_RANGE_STRING_DETAIL_COLLECTION_TRAITS_HPP
#define BOOST_RANGE_STRING_DETAIL_COLLECTION_TRAITS_HPP

#include <boost/algorithm/string/config.hpp>
#include <cstddef>
#include <string>
#include <boost/type_traits/is_array.hpp>
#include <boost/type_traits/is_pointer.hpp>
#include <boost/type_traits/is_const.hpp>
#include <boost/type_traits/is_convertible.hpp>
#include <boost/type_traits/remove_pointer.hpp>
#include <boost/type_traits/remove_cv.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/identity.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/fold.hpp>
#include <boost/detail/iterator.hpp>
#include <boost/algorithm/string/yes_no_type.hpp>

// Container traits implementation ---------------------------------------------------------

namespace boost {
    namespace algorithm {
        namespace detail {

// Default collection traits -----------------------------------------------------------------

            // Default collection helper
            /*
                Wraps std::container compliant containers
            */
            template< typename ContainerT >
            struct default_container_traits
            {
                typedef BOOST_STRING_TYPENAME ContainerT::value_type value_type;
                typedef BOOST_STRING_TYPENAME ContainerT::iterator iterator;
                typedef BOOST_STRING_TYPENAME ContainerT::const_iterator const_iterator;
                typedef BOOST_STRING_TYPENAME
                    ::boost::mpl::if_< ::boost::is_const<ContainerT>,
                        const_iterator,
                        iterator
                    >::type result_iterator;
                typedef BOOST_STRING_TYPENAME ContainerT::difference_type difference_type;
                typedef BOOST_STRING_TYPENAME ContainerT::size_type size_type;

                // static operations
                template< typename C >
                static size_type size( const C& c )
                {
                    return c.size();
                }

                template< typename C >
                static bool empty( const C& c )
                {
                    return c.empty();
                }

#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING

                template< typename C >
                static iterator begin( C& c )
                {
                    return c.begin();
                }

                template< typename C >
                static const_iterator begin( const C& c )
                {
                    return c.begin();
                }

                template< typename C >
                static iterator end( C& c )
                {
                    return c.end();
                }

                template< typename C >
                static const_iterator end( const C& c )
                {
                    return c.end();
                }

#else // BOOST_NO_FUNCTION_TEMPLATE_ORDERING

                template< typename C >
                static result_iterator begin( C& c )
                {
                    return c.begin();
                }

                template< typename C >
                static result_iterator end( C& c )
                {
                    return c.end();
                }

#endif // BOOST_NO_FUNCTION_TEMPLATE_ORDERING

            };

            template<typename T>
            struct default_container_traits_selector
            {
                typedef default_container_traits<T> type;
            };

// Pair container traits ---------------------------------------------------------------------

            // pair selector
            template< typename T, typename U >
            yes_type is_pair_impl( const std::pair<T,U>* );
            no_type is_pair_impl( ... );

            template<typename T> struct is_pair
            {
            private:
                static T* t;
            public:
                BOOST_STATIC_CONSTANT( bool, value=
                    sizeof(is_pair_impl(t))==sizeof(yes_type) );
            };

            // pair helper
            template< typename PairT >
            struct pair_container_traits
            {
                typedef BOOST_STRING_TYPENAME PairT::first_type element_type;

                typedef BOOST_STRING_TYPENAME ::boost::detail::
                    iterator_traits<element_type>::value_type value_type;
                typedef std::size_t size_type;
                typedef BOOST_STRING_TYPENAME ::boost::detail::
                    iterator_traits<element_type>::difference_type difference_type;

                typedef element_type iterator;
                typedef element_type const_iterator;
                typedef element_type result_iterator;

                // static operations
                template< typename P >
                static size_type size( const P& p )
                {
                    difference_type diff = std::distance( p.first, p.second );
                    if ( diff < 0 )
                        return 0;
                    else
                        return diff;
                }

                template< typename P >
                static bool empty( const P& p )
                {
                    return p.first==p.second;
                }

                template< typename P >
                static const_iterator begin( const P& p )
                {
                    return p.first;
                }

                template< typename P >
                static const_iterator end( const P& p )
                {
                    return p.second;
                }
            }; // 'pair_container_helper'

            template<typename T>
            struct pair_container_traits_selector
            {
                typedef pair_container_traits<T> type;
            };

// Array container traits ---------------------------------------------------------------

#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
            // array traits ( partial specialization )
            template< typename T >
            struct array_traits;

            template< typename T, std::size_t sz >
            struct array_traits<T[sz]>
            {
                // typedef
                typedef T* iterator;
                typedef const T* const_iterator;
                typedef T value_type;
                typedef std::size_t size_type;
                typedef std::ptrdiff_t difference_type;

                // size of the array ( static );
                BOOST_STATIC_CONSTANT( size_type, array_size = sz );
            };

#else // BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION

            // array traits ( no partial specialization )
            /*
                without parial specialization we are able to
                provide support only for a limited number of
                types. Currently the primitive numeric types
                are supported
            */
            template< typename T, typename BaseT >
            struct array_traits_impl
            {
                typedef BaseT value_type;
                typedef BaseT* iterator;
                typedef const BaseT* const_iterator;
                typedef std::size_t size_type;
                typedef std::ptrdiff_t difference_type;

                // size of the array
                BOOST_STATIC_CONSTANT( size_type, array_size = sizeof(T)/sizeof(BaseT) );
            };

            template< typename T, typename BaseT >
            struct array_traits_impl_selector
            {
                typedef array_traits_impl<T,BaseT> type;
            };

            struct array_traits_void
            {
                typedef void type;
            };

            template< typename T, typename BaseT >
            struct array_traits_cv_selector
            {
                typedef BOOST_STRING_TYPENAME
                    ::boost::mpl::eval_if<
                        ::boost::is_convertible<T,BaseT*>,
                        array_traits_impl_selector<T,BaseT>,
                        ::boost::mpl::eval_if<
                            ::boost::is_convertible<T,const BaseT*>,
                                array_traits_impl_selector<T, const BaseT>,
                                ::boost::mpl::eval_if<
                                    ::boost::is_convertible<T, volatile BaseT*>,
                                    array_traits_impl_selector<T, volatile BaseT>,
                                    array_traits_impl_selector<T, const volatile BaseT>
                                >
                            >
                    >::type type;
            };

            template< typename T >
            struct array_traits_select
            {
                template< typename T1, typename T2 >
                struct apply
                {
                    typedef BOOST_STRING_TYPENAME
                        ::boost::mpl::eval_if<
                            ::boost::is_convertible<T,const volatile T2*>,
                            array_traits_cv_selector<T,T2>,
                            ::boost::mpl::identity<T1> >::type type;
                };
            };

            template< typename T >
            struct array_traits_selector
            {
            private:
                // supported array base types
#ifndef BOOST_NO_INTRINSIC_WCHAR_T
                typedef BOOST_STRING_TYPENAME
                    ::boost::mpl::vector10<
                        wchar_t,
#else // BOOST_NO_INTRINSIC_WCHAR_T
                typedef BOOST_STRING_TYPENAME
                    ::boost::mpl::vector9<
#endif // BOOST_NO_INTRINSIC_WCHAR_T
                        char,
                        signed char,
                        unsigned char,
                        signed short,
                        unsigned short,
                        signed int,
                        unsigned int,
                        signed long,
                        unsigned long
                >::type array_base_types;

            public:
                typedef BOOST_STRING_TYPENAME
                    ::boost::mpl::fold<
                        array_base_types,
                        ::boost::algorithm::detail::array_traits_void,
                        ::boost::algorithm::detail::array_traits_select<T> >::type type;
            };

            template< typename T >
            struct array_traits
            {
                typedef BOOST_STRING_TYPENAME
                    array_traits_selector<T>::type traits_type;

                typedef BOOST_STRING_TYPENAME
                    traits_type::value_type value_type;
                typedef BOOST_STRING_TYPENAME
                    traits_type::iterator iterator;
                typedef BOOST_STRING_TYPENAME
                    traits_type::const_iterator const_iterator;
                typedef BOOST_STRING_TYPENAME
                    traits_type::size_type size_type;
                typedef BOOST_STRING_TYPENAME
                    traits_type::difference_type difference_type;

                BOOST_STATIC_CONSTANT( size_type, array_size = traits_type::array_size );
            };

#endif // BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION

            // array lenght resolving
            /*
                Lenght of string contained in a static array could
                be different from the size of the array.
                For string processing we need the lenght without
                terminating 0.

                Therefore, the lenght is calulated for char and wchar_t
                using char_traits, rather then simply returning
                the array size.
            */
            template< typename T >
            struct array_length_selector
            {
                template< typename TraitsT >
                struct array_length
                {
                    typedef BOOST_STRING_TYPENAME
                        TraitsT::size_type size_type;

                    BOOST_STATIC_CONSTANT(
                        size_type,
                        array_size=TraitsT::array_size );

                    template< typename A >
                    static size_type length( const A& )
                    {
                        return array_size;
                    }

                    template< typename A >
                    static bool empty( const A& )
                    {
                        return array_size==0;
                    }
                };
            };

            // specialization for char
            template<>
            struct array_length_selector<char>
            {
                template< typename TraitsT >
                struct array_length
                {
                    typedef BOOST_STRING_TYPENAME
                        TraitsT::size_type size_type;

                    template< typename A >
                    static size_type length( const A& a )
                    {
                        if ( a==0 )
                            return 0;
                        else
                            return std::char_traits<char>::length(a);
                    }

                    template< typename A >
                    static bool empty( const A& a )
                    {
                        return a==0 || a[0]==0;
                    }
                };
            };

            // specialization for wchar_t
            template<>
            struct array_length_selector<wchar_t>
            {
                template< typename TraitsT >
                struct array_length
                {
                    typedef BOOST_STRING_TYPENAME
                        TraitsT::size_type size_type;

                    template< typename A >
                    static size_type length( const A& a )
                    {
                        if ( a==0 )
                            return 0;
                        else
                            return std::char_traits<wchar_t>::length(a);
                    }

                    template< typename A >
                    static bool empty( const A& a )
                    {
                        return a==0 || a[0]==0;
                    }
                };
            };

            template< typename T >
            struct array_container_traits
            {
            private:
                // resolve array traits
                typedef array_traits<T> traits_type;

            public:
                typedef BOOST_STRING_TYPENAME
                    traits_type::value_type value_type;
                typedef BOOST_STRING_TYPENAME
                    traits_type::iterator iterator;
                typedef BOOST_STRING_TYPENAME
                    traits_type::const_iterator const_iterator;
                typedef BOOST_STRING_TYPENAME
                    traits_type::size_type size_type;
                typedef BOOST_STRING_TYPENAME
                    traits_type::difference_type difference_type;

                typedef BOOST_STRING_TYPENAME
                    ::boost::mpl::if_< ::boost::is_const<T>,
                        const_iterator,
                        iterator
                    >::type result_iterator;

            private:
                // resolve array size
                typedef BOOST_STRING_TYPENAME
                    ::boost::remove_cv<value_type>::type char_type;
                typedef BOOST_STRING_TYPENAME
                    array_length_selector<char_type>::
                        BOOST_NESTED_TEMPLATE array_length<traits_type> array_length_type;

            public:
                BOOST_STATIC_CONSTANT( size_type, array_size = traits_type::array_size );

                // static operations
                template< typename A >
                static size_type size( const A& a )
                {
                    return array_length_type::length(a);
                }

                template< typename A >
                static bool empty( const A& a )
                {
                    return array_length_type::empty(a);
                }

#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING

                template< typename A >
                static iterator begin( A& a )
                {
                    return a;
                }

                template< typename A >
                static const_iterator begin( const A& a )
                {
                    return a;
                }

                template< typename A >
                static iterator end( A& a )
                {
                    return a+array_length_type::length(a);
                }

                template< typename A >
                static const_iterator end( const A& a )
                {
                    return a+array_length_type::length(a);
                }

#else // BOOST_NO_FUNCTION_TEMPLATE_ORDERING

                template< typename A >
                static result_iterator begin( A& a )
                {
                    return a;
                }

                template< typename A >
                static result_iterator end( A& a )
                {
                    return a+array_length_type::length(a);
                }

#endif // BOOST_NO_FUNCTION_TEMPLATE_ORDERING

            };

            template<typename T>
            struct array_container_traits_selector
            {
                typedef array_container_traits<T> type;
            };

// Pointer container traits ---------------------------------------------------------------

            template<typename T>
            struct pointer_container_traits
            {
                typedef BOOST_STRING_TYPENAME
                    ::boost::remove_pointer<T>::type value_type;

                typedef BOOST_STRING_TYPENAME
                    ::boost::remove_cv<value_type>::type char_type;
                typedef ::std::char_traits<char_type> char_traits;

                typedef value_type* iterator;
                typedef const value_type* const_iterator;
                typedef std::ptrdiff_t difference_type;
                typedef std::size_t size_type;

                typedef BOOST_STRING_TYPENAME
                    ::boost::mpl::if_< ::boost::is_const<T>,
                        const_iterator,
                        iterator
                    >::type result_iterator;

                // static operations
                template< typename P >
                static size_type size( const P& p )
                {
                    if ( p==0 )
                        return 0;
                    else
                        return char_traits::length(p);
                }

                template< typename P >
                static bool empty( const P& p )
                {
                    return p==0 || p[0]==0;
                }

#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING

                template< typename P >
                static iterator begin( P& p )
                {
                    return p;
                }

                template< typename P >
                static const_iterator begin( const P& p )
                {
                    return p;
                }

                template< typename P >
                static iterator end( P& p )
                {
                    if ( p==0 )
                        return p;
                    else
                        return p+char_traits::length(p);
                }

                template< typename P >
                static const_iterator end( const P& p )
                {
                    if ( p==0 )
                        return p;
                    else
                        return p+char_traits::length(p);
                }

#else // BOOST_NO_FUNCTION_TEMPLATE_ORDERING

                template< typename P >
                static result_iterator begin( P& p )
                {
                    return p;
                }

                template< typename P >
                static result_iterator end( P& p )
                {
                    if ( p==0 )
                        return p;
                    else
                        return p+char_traits::length(p);
                }

#endif // BOOST_NO_FUNCTION_TEMPLATE_ORDERING
            };

            template<typename T>
            struct pointer_container_traits_selector
            {
                typedef pointer_container_traits<T> type;
            };

        } // namespace detail
    } // namespace algorithm
} // namespace boost

#endif  // BOOST_STRING_DETAIL_COLLECTION_HPP

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
//
// Utils.cpp
//

#include "Utils.hpp"
#include "lz4/lz4.h"
#include <string>
#include <cassert>
#include <limits>
#include <stdexcept>
#include <cctype>
#include <boost/asio/ip/address.hpp>
#include <boost/foreach.hpp>

namespace network {
    namespace Utils {

        std::string Encode(const std::string& in)
        {
            return ByteStuffingEncode(in) + static_cast<char>(NETWORK_UTILS_DELIMITOR);
        }

        std::string Decode(const std::string& in)
        {
            return ByteStuffingDecode(in);
        }

        std::string ByteStuffingEncode(const std::string& in)
        {
            std::string out;
			out.reserve(in.size() * 1.2);

			BOOST_FOREACH(const char& c, in) {
				if (c == 0x7e || c == 0x7d) {
                    out += 0x7d;
                    out += c ^ 0x20;
                } else {
                    out += c;
                }
			}

            return out;
        }

        std::string ByteStuffingDecode(const std::string& in)
        {
            std::string out;
			out.reserve(in.size());

            bool escape = false;

			BOOST_FOREACH(const char& c, in) {
				if (escape) {
                    out += c ^ 0x20;
                    escape = false;
                } else if (!(escape = (c == 0x7d))) {
                    out += c;
                }
			}

            return out;
        }

        std::string ToHexString(const std::string& in)
        {
            std::string out;

			BOOST_FOREACH(const char& c, in) {
				out += (boost::format("%X ") % (int)c).str();
			}

            return out;
        }

        bool IsPrivateAddress(const std::string& in)
        {
            typedef boost::asio::ip::address address;
            static auto private_a_from = address::from_string("10.0.0.0");
            static auto private_a_to   = address::from_string("10.255.255.255");
            static auto private_b_from = address::from_string("172.16.0.0");
            static auto private_b_to   = address::from_string("172.31.255.255");
            static auto private_c_from = address::from_string("192.168.0.0");
            static auto private_c_to   = address::from_string("192.168.255.255");

            auto addr = address::from_string(in);
            return (private_c_from <= addr && addr <= private_c_to) ||
                   (private_b_from <= addr && addr <= private_b_to) ||
                   (private_a_from <= addr && addr <= private_a_to);
        }

        static const char b64_table[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        static const char reverse_table[128] = {
           64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
           64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
           64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63,
           52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64,
           64,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
           15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 64,
           64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
           41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64
        };

        std::string Base64Encode(const std::string &bindata)
        {
           if (bindata.empty())
              return "";

           using std::string;
           using std::numeric_limits;

           if (bindata.size() > (numeric_limits<string::size_type>::max() / 4u) * 3u) {
              throw std::length_error("Converting too large a string to base64.");
           }

           const std::size_t binlen = bindata.size();
           // Use = signs so the end is properly padded.
           string retval((((binlen + 2) / 3) * 4), '=');
           std::size_t outpos = 0;
           int bits_collected = 0;
           uint32_t accumulator = 0;
           const string::const_iterator binend = bindata.end();

           for (string::const_iterator i = bindata.begin(); i != binend; ++i) {
              accumulator = (accumulator << 8) | (*i & 0xffu);
              bits_collected += 8;
              while (bits_collected >= 6) {
                 bits_collected -= 6;
                 retval[outpos++] = b64_table[(accumulator >> bits_collected) & 0x3fu];
              }
           }
           if (bits_collected > 0) { // Any trailing bits that are missing.
              assert(bits_collected < 6);
              accumulator <<= 6 - bits_collected;
              retval[outpos++] = b64_table[accumulator & 0x3fu];
           }
           assert(outpos >= (retval.size() - 2));
           assert(outpos <= retval.size());
           return retval;
        }

        std::string Base64Decode(const ::std::string &ascdata)
        {
           if (ascdata.empty())
               return "";

           using std::string;
           string retval;
           const string::const_iterator last = ascdata.end();
           int bits_collected = 0;
           uint32_t accumulator = 0;

           BOOST_FOREACH(const int c, ascdata) {
              if (::std::isspace(c) || c == '=') {
                 // Skip whitespace and padding. Be liberal in what you accept.
                 continue;
              }
              if ((c > 127) || (c < 0) || (reverse_table[c] > 63)) {
                 throw ::std::invalid_argument("This contains characters not legal in a base64 encoded string.");
              }
              accumulator = (accumulator << 6) | reverse_table[c];
              bits_collected += 6;
              if (bits_collected >= 8) {
                 bits_collected -= 8;
                 retval += (char)((accumulator >> bits_collected) & 0xffu);
              }
           }
           return retval;
        }

        std::string LZ4Compress(const std::string& in)
        {
            std::unique_ptr<char[]> outbuf(new char [LZ4_compressBound(in.size())]);
            size_t out_size = LZ4_compress(in.data(), outbuf.get(), in.size());
            return std::string(outbuf.get(), out_size);
        }

        std::string LZ4Uncompress(const std::string& in, size_t size)
        {
            std::unique_ptr<char[]> outbuf(new char [size]);
            LZ4_uncompress(in.data(), outbuf.get(), size);
            return std::string(outbuf.get(), size);
        }

		int wildcmp(const char *wild, const char *string) {
			// Written by Jack Handy - jakkhandy@hotmail.com
			const char *cp = NULL, *mp = NULL;

			while ((*string) && (*wild != '*')) {
				if ((*wild != *string) && (*wild != '?')) {
					return 0;
				}
				wild++;
				string++;
			}

			while (*string) {
				if (*wild == '*') {
					if (!*++wild) {
						return 1;
					}
					mp = wild;
					cp = string+1;
				} else if ((*wild == *string) || (*wild == '?')) {
					wild++;
					string++;
				} else {
					wild = mp;
					string = cp++;
				}
			}

			while (*wild == '*') {
				wild++;
			}
			return !*wild;
		}

		bool MatchWithWildcard(const std::string& pattern, const std::string& text)
		{
			return wildcmp(pattern.c_str(), text.c_str());
		}

    }
}


text:
/// \file type.hpp

#ifndef COLORUTIL_TYPE_HPP
#define COLORUTIL_TYPE_HPP

#include <Eigen/Core>

namespace colorutil
{
    /// \brief RGB
    ///
    /// \details Each value is defined in [0, 1].
    using RGB = Eigen::Vector3d;

    /// \brief HSL
    ///
    /// \details Each value is defined in [0, 1].
    using HSL = Eigen::Vector3d;

    /// \brief CIEXYZ
    using XYZ = Eigen::Vector3d;

    /// \brief CIELAB
    using Lab = Eigen::Vector3d;
} // namespace colorutil

#endif // COLORUTIL_TYPE_HPP