deleted tabs
[libcds.git] / cds / container / lazy_list_nogc.h
index b10f44c7465bda2d65c51bbcad29c773e52b9361..551b53d41fb73f080d70a6694777096357455b11 100644 (file)
-//$$CDS-header$$
+/*
+    This file is a part of libcds - Concurrent Data Structures library
 
-#ifndef __CDS_CONTAINER_LAZY_LIST_NOGC_H
-#define __CDS_CONTAINER_LAZY_LIST_NOGC_H
+    (C) Copyright Maxim Khizhinsky (libcds.dev@gmail.com) 2006-2016
 
-#include <cds/container/lazy_list_base.h>
-#include <cds/intrusive/lazy_list_nogc.h>
-#include <cds/container/details/make_lazy_list.h>
-#include <cds/details/std/memory.h>
+    Source code repo: http://github.com/khizmax/libcds/
+    Download: http://sourceforge.net/projects/libcds/files/
 
-namespace cds { namespace container {
+    Redistribution and use in source and binary forms, with or without
+    modification, are permitted provided that the following conditions are met:
 
-    //@cond
-    namespace details {
+    * Redistributions of source code must retain the above copyright notice, this
+      list of conditions and the following disclaimer.
 
-        template <typename T, class Traits>
-        struct make_lazy_list_nogc: public make_lazy_list<gc::nogc, T, Traits>
-        {
-            typedef make_lazy_list<cds::gc::nogc, T, Traits>  base_maker;
-            typedef typename base_maker::node_type node_type;
+    * 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.
 
-            struct type_traits: public base_maker::type_traits
-            {
-                typedef typename base_maker::node_deallocator    disposer;
-            };
+    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.
+*/
 
-            typedef intrusive::LazyList<cds::gc::nogc, node_type, type_traits>  type;
-        };
+#ifndef CDSLIB_CONTAINER_LAZY_LIST_NOGC_H
+#define CDSLIB_CONTAINER_LAZY_LIST_NOGC_H
 
-    }   // namespace details
-    //@endcond
+#include <memory>
+#include <cds/container/details/lazy_list_base.h>
+#include <cds/intrusive/lazy_list_nogc.h>
+#include <cds/container/details/make_lazy_list.h>
+
+namespace cds { namespace container {
 
     /// Lazy ordered single-linked list (template specialization for gc::nogc)
     /** @ingroup cds_nonintrusive_list
         \anchor cds_nonintrusive_LazyList_nogc
 
-        This specialization is intended for so-called persistent usage when no item
+        This specialization is so-called append-only when no item
         reclamation may be performed. The class does not support deleting of list item.
 
-        Usually, ordered single-linked list is used as a building block for the hash table implementation.
-        The complexity of searching is <tt>O(N)</tt>.
-
-        See \ref cds_nonintrusive_LazyList_gc "LazyList" for description of template parameters.
+        The list can be ordered if \p Traits::sort is \p true that is default
+        or unordered otherwise. Unordered list can be maintained by \p equal_to
+        relationship (\p Traits::equal_to), but for the ordered list \p less
+        or \p compare relations should be specified in \p Traits.
 
-        The interface of the specialization is a little different.
+        See @ref cds_nonintrusive_LazyList_gc "cds::container::LazyList<cds::gc::nogc, T, Traits>"
     */
-    template <typename T, typename Traits>
-    class LazyList<gc::nogc, T, Traits>:
+    template <
+        typename T,
+#ifdef CDS_DOXYGEN_INVOKED
+        typename Traits = lazy_list::traits
+#else
+        typename Traits
+#endif
+    >
+    class LazyList<cds::gc::nogc, T, Traits>:
 #ifdef CDS_DOXYGEN_INVOKED
         protected intrusive::LazyList< gc::nogc, T, Traits >
 #else
-        protected details::make_lazy_list_nogc< T, Traits >::type
+        protected details::make_lazy_list< cds::gc::nogc, T, Traits >::type
 #endif
     {
         //@cond
-        typedef details::make_lazy_list_nogc< T, Traits > options;
-        typedef typename options::type  base_class;
+        typedef details::make_lazy_list< cds::gc::nogc, T, Traits > maker;
+        typedef typename maker::type  base_class;
         //@endcond
 
     public:
-        typedef T                                   value_type      ;   ///< Type of value stored in the list
-        typedef typename base_class::gc             gc              ;   ///< Garbage collector used
-        typedef typename base_class::back_off       back_off        ;   ///< Back-off strategy used
-        typedef typename options::allocator_type    allocator_type  ;   ///< Allocator type used for allocate/deallocate the nodes
-        typedef typename base_class::item_counter   item_counter    ;   ///< Item counting policy used
-        typedef typename options::key_comparator    key_comparator  ;   ///< key comparison functor
-        typedef typename base_class::memory_model   memory_model    ;   ///< Memory ordering. See cds::opt::memory_model option
+        typedef cds::gc::nogc gc;  ///< Garbage collector
+        typedef T      value_type; ///< Type of value stored in the list
+        typedef Traits traits;     ///< List traits
 
-    protected:
-        //@cond
-        typedef typename base_class::value_type     node_type;
-        typedef typename options::cxx_allocator     cxx_allocator;
-        typedef typename options::node_deallocator  node_deallocator;
-        typedef typename options::type_traits::compare  intrusive_key_comparator;
+        typedef typename base_class::back_off     back_off;         ///< Back-off strategy used
+        typedef typename maker::allocator_type    allocator_type;   ///< Allocator type used for allocate/deallocate the nodes
+        typedef typename base_class::item_counter item_counter;     ///< Item counting policy used
+        typedef typename maker::key_comparator    key_comparator;   ///< key comparing functor
+        typedef typename base_class::memory_model memory_model;     ///< Memory ordering. See cds::opt::memory_model option
+        typedef typename base_class::stat         stat;             ///< Internal statistics
 
-        typedef typename base_class::node_type      head_type;
-        //@endcond
+        static CDS_CONSTEXPR bool const c_bSort = base_class::c_bSort; ///< List type: ordered (\p true) or unordered (\p false)
 
-    protected:
         //@cond
-#   ifndef CDS_CXX11_LAMBDA_SUPPORT
-        struct ensure_functor
-        {
-            node_type * m_pItemFound;
-
-            ensure_functor()
-                : m_pItemFound( null_ptr<node_type *>() )
-            {}
-
-            void operator ()(bool, node_type& item, node_type& )
-            {
-                m_pItemFound = &item;
-            }
+        // Rebind traits (split-list support)
+        template <typename... Options>
+        struct rebind_traits {
+            typedef LazyList<
+                gc
+                , value_type
+                , typename cds::opt::make_options< traits, Options...>::type
+            > type;
         };
-#   endif
+
+        // Stat selector
+        template <typename Stat>
+        using select_stat_wrapper = typename base_class::template select_stat_wrapper< Stat >;
         //@endcond
 
     protected:
         //@cond
-        static node_type * alloc_node()
-        {
-            return cxx_allocator().New();
-        }
-
-        static node_type * alloc_node( value_type const& v )
-        {
-            return cxx_allocator().New( v );
-        }
-
-#   ifdef CDS_EMPLACE_SUPPORT
-        template <typename... Args>
-        static node_type * alloc_node( Args&&... args )
-        {
-            return cxx_allocator().MoveNew( std::forward<Args>(args)... );
-        }
-#   endif
+        typedef typename base_class::value_type     node_type;
+        typedef typename maker::cxx_allocator       cxx_allocator;
+        typedef typename maker::node_deallocator    node_deallocator;
+        typedef typename base_class::key_comparator intrusive_key_comparator;
 
-        static void free_node( node_type * pNode )
-        {
-            cxx_allocator().Delete( pNode );
-        }
+        typedef typename base_class::node_type      head_type;
 
         struct node_disposer {
             void operator()( node_type * pNode )
@@ -127,26 +118,6 @@ namespace cds { namespace container {
             }
         };
         typedef std::unique_ptr< node_type, node_disposer >     scoped_node_ptr;
-
-        head_type& head()
-        {
-            return base_class::m_Head;
-        }
-
-        head_type const& head() const
-        {
-            return base_class::m_Head;
-        }
-
-        head_type& tail()
-        {
-            return base_class::m_Tail;
-        }
-
-        head_type const& tail() const
-        {
-            return base_class::m_Tail;
-        }
         //@endcond
 
     protected:
@@ -157,7 +128,7 @@ namespace cds { namespace container {
             typedef typename base_class::template iterator_type<IsConst>    iterator_base;
 
             iterator_type( head_type const& pNode )
-                : iterator_base( const_cast<head_type *>(&pNode) )
+                : iterator_base( const_cast<head_type *>(&pNode))
             {}
 
             explicit iterator_type( const iterator_base& it )
@@ -185,7 +156,7 @@ namespace cds { namespace container {
             value_ptr operator ->() const
             {
                 typename iterator_base::value_ptr p = iterator_base::operator ->();
-                return p ? &(p->m_Value) : null_ptr<value_ptr>();
+                return p ? &(p->m_Value) : nullptr;
             }
 
             value_ref operator *() const
@@ -220,6 +191,8 @@ namespace cds { namespace container {
         //@endcond
 
     public:
+    ///@name Forward iterators
+    //@{
         /// Returns a forward iterator addressing the first element in a list
         /**
             For empty list \code begin() == end() \endcode
@@ -238,7 +211,7 @@ namespace cds { namespace container {
         */
         iterator begin()
         {
-            iterator it( head() );
+            iterator it( head());
             ++it    ;   // skip dummy head node
             return it;
         }
@@ -256,55 +229,47 @@ namespace cds { namespace container {
         }
 
         /// Returns a forward const iterator addressing the first element in a list
-        //@{
         const_iterator begin() const
         {
-            const_iterator it( head() );
+            const_iterator it( head());
             ++it    ;   // skip dummy head node
             return it;
         }
-        const_iterator cbegin()
+
+        /// Returns a forward const iterator addressing the first element in a list
+        const_iterator cbegin() const
         {
-            const_iterator it( head() );
+            const_iterator it( head());
             ++it    ;   // skip dummy head node
             return it;
         }
-        //@}
 
         /// Returns an const iterator that addresses the location succeeding the last element in a list
-        //@{
         const_iterator end() const
         {
             return const_iterator( tail());
         }
-        const_iterator cend()
-        {
-            return const_iterator( tail());
-        }
-        //@}
 
-    protected:
-        //@cond
-        iterator node_to_iterator( node_type * pNode )
+        /// Returns an const iterator that addresses the location succeeding the last element in a list
+        const_iterator cend() const
         {
-            if ( pNode )
-                return iterator( *pNode );
-            return end();
+            return const_iterator( tail());
         }
-        //@endcond
+    //@}
 
     public:
         /// Default constructor
-        /**
-            Initialize empty list
-        */
         LazyList()
         {}
 
-        /// List desctructor
-        /**
-            Clears the list
-        */
+        //@cond
+        template <typename Stat, typename = std::enable_if<std::is_same<stat, lazy_list::wrapped_stat<Stat>>::value >>
+        explicit LazyList( Stat& st )
+            : base_class( st )
+        {}
+        //@endcond
+
+        /// Desctructor clears the list
         ~LazyList()
         {
             clear();
@@ -318,66 +283,106 @@ namespace cds { namespace container {
             Return an iterator pointing to inserted item if success \ref end() otherwise
         */
         template <typename Q>
-        iterator insert( Q const& val )
+        iterator insert( Q&& val )
         {
-            return node_to_iterator( insert_at( head(), val ) );
+            return node_to_iterator( insert_at( head(), std::forward<Q>( val )));
         }
 
-#   ifdef CDS_EMPLACE_SUPPORT
-        /// Inserts data of type \ref value_type constructed with <tt>std::forward<Args>(args)...</tt>
+        /// Inserts data of type \p value_type created from \p args
         /**
             Return an iterator pointing to inserted item if success \ref end() otherwise
-
-            This function is available only for compiler that supports
-            variadic template and move semantics
         */
         template <typename... Args>
         iterator emplace( Args&&... args )
         {
             return node_to_iterator( emplace_at( head(), std::forward<Args>(args)... ));
         }
-#   endif
 
-        /// Ensures that the item \p val exists in the list
+        /// Updates the item
         /**
-            The operation inserts new item if the key \p val is not found in the list.
-            Otherwise, the function returns an iterator that points to item found.
+            If \p key is not in the list and \p bAllowInsert is \p true,
+            the function inserts a new item.
+            Otherwise, the function returns an iterator pointing to the item found.
 
             Returns <tt> std::pair<iterator, bool>  </tt> where \p first is an iterator pointing to
             item found or inserted, \p second is true if new item has been added or \p false if the item
             already is in the list.
         */
         template <typename Q>
-        std::pair<iterator, bool> ensure( Q const& val )
+        std::pair<iterator, bool> update( Q&& val, bool bAllowInsert = true )
         {
-            std::pair< node_type *, bool > ret = ensure_at( head(), val );
+            std::pair< node_type *, bool > ret = update_at( head(), std::forward<Q>( val ), bAllowInsert );
             return std::make_pair( node_to_iterator( ret.first ), ret.second );
         }
+        //@cond
+        template <typename Q>
+        CDS_DEPRECATED("ensure() is deprecated, use update()")
+        std::pair<iterator, bool> ensure( Q const& val )
+        {
+            return update( val, true );
+        }
+        //@endcond
 
-        /// Find the key \p val
-        /** \anchor cds_nonintrusive_LazyList_nogc_find
-            The function searches the item with key equal to \p val
+        /// Checks whether the list contains \p key
+        /**
+            The function searches the item with key equal to \p key
             and returns an iterator pointed to item found if the key is found,
             and \ref end() otherwise
         */
         template <typename Q>
+        iterator contains( Q const& key )
+        {
+            return node_to_iterator( find_at( head(), key, intrusive_key_comparator()));
+        }
+        //@cond
+        template <typename Q>
+        CDS_DEPRECATED("deprecated, use contains()")
         iterator find( Q const& key )
         {
-            return node_to_iterator( find_at( head(), key, intrusive_key_comparator() ));
+            return contains( key );
         }
+        //@endcond
 
-        /// Finds the key \p val using \p pred predicate for searching
+        /// Checks whether the map contains \p key using \p pred predicate for searching (ordered list version)
         /**
-            The function is an analog of \ref cds_nonintrusive_LazyList_nogc_find "find(Q const&)"
-            but \p pred is used for key comparing.
+            The function is an analog of <tt>contains( key )</tt> but \p pred is used for key comparing.
             \p Less functor has the interface like \p std::less.
-            \p pred must imply the same element order as the comparator used for building the list.
+            \p Less must imply the same element order as the comparator used for building the list.
         */
-        template <typename Q, typename Less>
-        iterator find_with( Q const& key, Less pred )
+        template <typename Q, typename Less, bool Sort = c_bSort>
+        typename std::enable_if<Sort, iterator>::type contains( Q const& key, Less pred )
+        {
+            CDS_UNUSED( pred );
+            return node_to_iterator( find_at( head(), key, typename maker::template less_wrapper<Less>::type()));
+        }
+        //@cond
+        template <typename Q, typename Less, bool Sort = c_bSort>
+        CDS_DEPRECATED("deprecated, use contains()")
+        typename std::enable_if<Sort, iterator>::type find_with( Q const& key, Less pred )
         {
-            return node_to_iterator( find_at( head(), key, typename options::template less_wrapper<Less>::type() ));
+            return contains( key, pred );
         }
+        //@endcond
+
+        /// Finds the key \p val using \p equal predicate for searching (unordered list version)
+        /**
+            The function is an analog of <tt>contains( key )</tt> but \p equal is used for key comparing.
+            \p Equal functor has the interface like \p std::equal_to.
+        */
+        template <typename Q, typename Equal, bool Sort = c_bSort>
+        typename std::enable_if<!Sort, iterator>::type contains( Q const& key, Equal equal )
+        {
+            CDS_UNUSED( equal );
+            return node_to_iterator( find_at( head(), key, typename maker::template equal_to_wrapper<Equal>::type()));
+        }
+        //@cond
+        template <typename Q, typename Equal, bool Sort = c_bSort>
+        CDS_DEPRECATED("deprecated, use contains()")
+        typename std::enable_if<!Sort, iterator>::type find_with( Q const& key, Equal equal )
+        {
+            return contains( key, equal );
+        }
+        //@endcond
 
         /// Check if the list is empty
         bool empty() const
@@ -387,10 +392,10 @@ namespace cds { namespace container {
 
         /// Returns list's item count
         /**
-            The value returned depends on opt::item_counter option. For atomicity::empty_item_counter,
+            The value returned depends on \p Traits::item_counter type. For \p atomicity::empty_item_counter,
             this function always returns 0.
 
-            <b>Warning</b>: even if you use real item counter and it returns 0, this fact is not mean that the list
+            @note Even if you use real item counter and it returns 0, this fact is not mean that the list
             is empty. To check list emptyness use \ref empty() method.
         */
         size_t size() const
@@ -398,10 +403,13 @@ namespace cds { namespace container {
             return base_class::size();
         }
 
+        /// Returns const reference to internal statistics
+        stat const& statistics() const
+        {
+            return base_class::statistics();
+        }
+
         /// Clears the list
-        /**
-            Post-condition: the list is empty
-        */
         void clear()
         {
             base_class::clear();
@@ -409,46 +417,97 @@ namespace cds { namespace container {
 
     protected:
         //@cond
+        static value_type& node_to_value( node_type& n )
+        {
+            return n.m_Value;
+        }
+
+        static node_type * alloc_node()
+        {
+            return cxx_allocator().New();
+        }
+
+        static node_type * alloc_node( value_type const& v )
+        {
+            return cxx_allocator().New( v );
+        }
+
+        template <typename... Args>
+        static node_type * alloc_node( Args&&... args )
+        {
+            return cxx_allocator().MoveNew( std::forward<Args>( args )... );
+        }
+
+        static void free_node( node_type * pNode )
+        {
+            cxx_allocator().Delete( pNode );
+        }
+
+        head_type& head()
+        {
+            return base_class::m_Head;
+        }
+
+        head_type const& head() const
+        {
+            return base_class::m_Head;
+        }
+
+        head_type& tail()
+        {
+            return base_class::m_Tail;
+        }
+
+        head_type const& tail() const
+        {
+            return base_class::m_Tail;
+        }
+
+        iterator node_to_iterator( node_type * pNode )
+        {
+            if ( pNode )
+                return iterator( *pNode );
+            return end();
+        }
+
+        iterator insert_node( node_type * pNode )
+        {
+            return node_to_iterator( insert_node_at( head(), pNode ));
+        }
+
         node_type * insert_node_at( head_type& refHead, node_type * pNode )
         {
-            assert( pNode != null_ptr<node_type *>() );
+            assert( pNode != nullptr );
             scoped_node_ptr p( pNode );
             if ( base_class::insert_at( &refHead, *p ))
                 return p.release();
 
-            return null_ptr<node_type *>();
+            return nullptr;
         }
 
         template <typename Q>
-        node_type * insert_at( head_type& refHead, Q const& val )
+        node_type * insert_at( head_type& refHead, Q&& val )
         {
-            return insert_node_at( refHead, alloc_node( val ));
+            return insert_node_at( refHead, alloc_node( std::forward<Q>( val )));
         }
 
-#   ifdef CDS_EMPLACE_SUPPORT
         template <typename... Args>
         node_type * emplace_at( head_type& refHead, Args&&... args )
         {
             return insert_node_at( refHead, alloc_node( std::forward<Args>(args)... ));
         }
-#   endif
+
         template <typename Q>
-        std::pair< node_type *, bool > ensure_at( head_type& refHead, Q const& val )
-        {
-            scoped_node_ptr pNode( alloc_node( val ));
-            node_type * pItemFound = null_ptr<node_type *>();
-
-#   ifdef CDS_CXX11_LAMBDA_SUPPORT
-            std::pair<bool, bool> ret = base_class::ensure_at( &refHead, *pNode,
-                [&pItemFound](bool, node_type& item, node_type&){ pItemFound = &item; });
-#   else
-            ensure_functor func;
-            std::pair<bool, bool> ret = base_class::ensure_at( &refHead, *pNode, boost::ref(func) );
-            pItemFound = func.m_pItemFound;
-#   endif
-            assert( pItemFound != null_ptr<node_type *>() );
-
-            if ( ret.first && ret.second )
+        std::pair< node_type *, bool > update_at( head_type& refHead, Q&& val, bool bAllowInsert )
+        {
+            scoped_node_ptr pNode( alloc_node( std::forward<Q>( val )));
+            node_type * pItemFound = nullptr;
+
+            std::pair<bool, bool> ret = base_class::update_at( &refHead, *pNode,
+                [&pItemFound](bool, node_type& item, node_type&) { pItemFound = &item; },
+                bAllowInsert );
+
+            if ( ret.second )
                 pNode.release();
 
             return std::make_pair( pItemFound, ret.second );
@@ -464,4 +523,4 @@ namespace cds { namespace container {
     };
 }} // namespace cds::container
 
-#endif // #ifndef __CDS_CONTAINER_LAZY_LIST_NOGC_H
+#endif // #ifndef CDSLIB_CONTAINER_LAZY_LIST_NOGC_H