Added internal statistics to MichaelSet/Map
[libcds.git] / cds / container / michael_kvlist_nogc.h
index 33a5017c5fab1e13fd2adc16d748800eca9eed60..f1b20003a42359fa5fd9441055712d24b62fcc93 100644 (file)
@@ -1,13 +1,40 @@
-//$$CDS-header$$
-
-#ifndef __CDS_CONTAINER_MICHAEL_KVLIST_NOGC_H
-#define __CDS_CONTAINER_MICHAEL_KVLIST_NOGC_H
-
-#include <cds/container/michael_list_base.h>
+/*
+    This file is a part of libcds - Concurrent Data Structures library
+
+    (C) Copyright Maxim Khizhinsky (libcds.dev@gmail.com) 2006-2016
+
+    Source code repo: http://github.com/khizmax/libcds/
+    Download: http://sourceforge.net/projects/libcds/files/
+    
+    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 CDSLIB_CONTAINER_MICHAEL_KVLIST_NOGC_H
+#define CDSLIB_CONTAINER_MICHAEL_KVLIST_NOGC_H
+
+#include <memory>
+#include <cds/container/details/michael_list_base.h>
 #include <cds/intrusive/michael_list_nogc.h>
 #include <cds/container/details/make_michael_kvlist.h>
-#include <cds/details/functor_wrapper.h>
-#include <cds/details/std/memory.h>
 
 namespace cds { namespace container {
 
@@ -20,12 +47,12 @@ namespace cds { namespace container {
             typedef make_michael_kvlist<cds::gc::nogc, K, T, Traits>  base_maker;
             typedef typename base_maker::node_type node_type;
 
-            struct type_traits: public base_maker::type_traits
+            struct intrusive_traits: public base_maker::intrusive_traits
             {
                 typedef typename base_maker::node_deallocator    disposer;
             };
 
-            typedef intrusive::MichaelList<cds::gc::nogc, node_type, type_traits>  type;
+            typedef intrusive::MichaelList<cds::gc::nogc, node_type, intrusive_traits>  type;
         };
 
     }   // namespace details
@@ -33,6 +60,7 @@ namespace cds { namespace container {
 
     /// Michael's ordered list (key-value pair, template specialization for gc::nogc)
     /** @ingroup cds_nonintrusive_list
+        @anchor cds_nonintrusive_MichaelKVList_nogc
 
         This specialization is intended for so-called persistent usage when no item
         reclamation may be performed. The class does not support deleting of list item.
@@ -48,7 +76,7 @@ namespace cds { namespace container {
         typename Key,
         typename Value,
 #ifdef CDS_DOXYGEN_INVOKED
-        typename Traits = michael_list::type_traits
+        typename Traits = michael_list::traits
 #else
         typename Traits
 #endif
@@ -61,99 +89,55 @@ namespace cds { namespace container {
 #endif
     {
         //@cond
-        typedef details::make_michael_kvlist_nogc< Key, Value, Traits > options;
-        typedef typename options::type  base_class;
+        typedef details::make_michael_kvlist_nogc< Key, Value, Traits > maker;
+        typedef typename maker::type  base_class;
         //@endcond
 
     public:
+        typedef cds::gc::nogc gc;         ///< Garbage collector used
+        typedef Traits        traits;     ///< List traits
+
 #ifdef CDS_DOXYGEN_INVOKED
         typedef Key                                 key_type        ;   ///< Key type
         typedef Value                               mapped_type     ;   ///< Type of value stored in the list
         typedef std::pair<key_type const, mapped_type> value_type   ;   ///< key/value pair stored in the list
 #else
-        typedef typename options::key_type          key_type;
-        typedef typename options::value_type        mapped_type;
-        typedef typename options::pair_type         value_type;
+        typedef typename maker::key_type          key_type;
+        typedef typename maker::value_type        mapped_type;
+        typedef typename maker::pair_type         value_type;
 #endif
 
-        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
-
-    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::atomic_node_ptr head_type;
-        //@endcond
+        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 comparison 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
 
-    private:
         //@cond
-#   ifndef CDS_CXX11_LAMBDA_SUPPORT
-        struct ensure_functor
-        {
-            node_type * m_pItemFound;
-
-            ensure_functor()
-                : m_pItemFound( nullptr )
-            {}
-
-            void operator ()(bool, node_type& item, node_type& )
-            {
-                m_pItemFound = &item;
-            }
+        // Rebind traits (split-list support)
+        template <typename... Options>
+        struct rebind_traits {
+            typedef MichaelKVList<
+                gc
+                , key_type, mapped_type
+                , typename cds::opt::make_options< traits, Options...>::type
+            > type;
         };
 
-        template <typename Func>
-        class find_functor: protected cds::details::functor_wrapper<Func>
-        {
-            typedef cds::details::functor_wrapper<Func> base_class;
-        public:
-            find_functor( Func f )
-                : base_class(f)
-            {}
-
-            template <typename Q>
-            void operator ()( node_type& node, Q&  )
-            {
-                base_class::get()( node.m_Data );
-            }
-        };
-#   endif
+        // Stat selector
+        template <typename Stat>
+        using select_stat_wrapper = typename base_class::template select_stat_wrapper< Stat >;
         //@endcond
 
     protected:
         //@cond
-        template <typename K>
-        static node_type * alloc_node(const K& key)
-        {
-            return cxx_allocator().New( key );
-        }
-
-        template <typename K, typename V>
-        static node_type * alloc_node( const K& key, const V& val )
-        {
-            return cxx_allocator().New( key, val );
-        }
-
-#ifdef CDS_EMPLACE_SUPPORT
-        template <typename K, typename... Args>
-        static node_type * alloc_node( K&& key, Args&&... args )
-        {
-            return cxx_allocator().MoveNew( std::forward<K>(key), 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 maker::intrusive_traits::compare  intrusive_key_comparator;
 
-        static void free_node( node_type * pNode )
-        {
-            cxx_allocator().Delete( pNode );
-        }
+        typedef typename base_class::atomic_node_ptr head_type;
 
         struct node_disposer {
             void operator()( node_type * pNode )
@@ -162,16 +146,6 @@ namespace cds { namespace container {
             }
         };
         typedef std::unique_ptr< node_type, node_disposer >     scoped_node_ptr;
-
-        head_type& head()
-        {
-            return base_class::m_pHead;
-        }
-
-        head_type const& head() const
-        {
-            return base_class::m_pHead;
-        }
         //@endcond
 
     protected:
@@ -264,17 +238,23 @@ namespace cds { namespace container {
         //@endcond
 
     public:
+    ///@name Forward iterators
+    //@{
         /// Forward iterator
         /**
-            The forward iterator for Michael's list based on gc::nogc has pre- and post-increment operators.
+            The forward iterator is safe: you may use it in multi-threaded enviromnent without any synchronization.
+
+            The forward iterator for Michael's list based on \p gc::nogc has pre- and post-increment operators.
 
             The iterator interface to access item data:
-            - <tt> operator -> </tt> - returns a pointer to \ref value_type for iterator
-            - <tt> operator *</tt> - returns a reference (a const reference for \p const_iterator) to \ref value_type for iterator
+            - <tt> operator -> </tt> - returns a pointer to \p value_type
+            - <tt> operator *</tt> - returns a reference (a const reference for \p const_iterator) to \p value_type
             - <tt> const key_type& key() </tt> - returns a key reference for iterator
             - <tt> mapped_type& val() </tt> - retuns a value reference for iterator (const reference for \p const_iterator)
 
-            For both functions the iterator should not be equal to <tt> end() </tt>
+            For both functions the iterator should not be equal to \p end().
+
+            @note \p end() iterator is not dereferenceable
         */
         typedef iterator_type<false>    iterator;
 
@@ -296,7 +276,7 @@ namespace cds { namespace container {
         /// Returns an iterator that addresses the location succeeding the last element in a list
         /**
             Do not use the value returned by <tt>end</tt> function to access any item.
-            Internally, <tt>end</tt> returning value equals to <tt>NULL</tt>.
+            Internally, <tt>end</tt> returning value equals to \p nullptr.
 
             The returned value can be used only to control reaching the end of the list.
             For empty list \code begin() == end() \endcode
@@ -307,38 +287,27 @@ namespace cds { namespace container {
         }
 
         /// Returns a forward const iterator addressing the first element in a list
-        //@{
         const_iterator begin() const
         {
             return const_iterator( head() );
         }
-        const_iterator cbegin()
+        /// Returns a forward const iterator addressing the first element in a list
+        const_iterator cbegin() const
         {
             return const_iterator( head() );
         }
-        //@}
 
         /// Returns an const iterator that addresses the location succeeding the last element in a list
-        //@{
         const_iterator end() const
         {
             return const_iterator();
         }
-        const_iterator cend()
+        /// Returns an const iterator that addresses the location succeeding the last element in a list
+        const_iterator cend() const
         {
             return const_iterator();
         }
-        //@}
-
-    protected:
-        //@cond
-        iterator node_to_iterator( node_type * pNode )
-        {
-            if ( pNode )
-                return iterator( *pNode );
-            return end();
-        }
-        //@endcond
+    //@}
 
     public:
         /// Default constructor
@@ -348,7 +317,14 @@ namespace cds { namespace container {
         MichaelKVList()
         {}
 
-        /// List desctructor
+        //@cond
+        template <typename Stat, typename = std::enable_if<std::is_same<stat, michael_list::wrapped_stat<Stat>>::value >>
+        explicit MichaelKVList( Stat& st )
+            : base_class( st )
+        {}
+        //@endcond
+
+        /// List destructor
         /**
             Clears the list
         */
@@ -407,8 +383,6 @@ namespace cds { namespace container {
             to the list's item inserted. <tt>item.second</tt> is a reference to item's value that may be changed.
             User-defined functor \p func should guarantee that during changing item's value no any other changes
             could be made on this list's item by concurrent threads.
-            The user-defined functor can be passed by reference using <tt>boost::ref</tt>
-            and it is called only if the inserting is successful.
 
             The key_type should be constructible from value of type \p K.
 
@@ -423,67 +397,86 @@ namespace cds { namespace container {
             Returns an iterator pointed to inserted value, or \p end() if inserting is failed
         */
         template <typename K, typename Func>
-        iterator insert_key( const K& key, Func func )
+        iterator insert_with( const K& key, Func func )
         {
-            return node_to_iterator( insert_key_at( head(), key, func ));
+            return node_to_iterator( insert_with_at( head(), key, func ));
         }
 
-        /// Ensures that the key \p key exists in the list
+        /// Updates the item
         /**
-            The operation inserts new item if the key \p key 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,
 
-            Returns <tt> std::pair<iterator, bool>  </tt> where \p first is an iterator pointing to
+            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 K>
-        std::pair<iterator, bool> ensure( const K& key )
+        std::pair<iterator, bool> update( K const& key, bool bAllowInsert = true )
         {
-            std::pair< node_type *, bool > ret = ensure_at( head(), key );
+            std::pair< node_type *, bool > ret = update_at( head(), key, bAllowInsert );
             return std::make_pair( node_to_iterator( ret.first ), ret.second );
         }
+        //@cond
+        template <typename K>
+        CDS_DEPRECATED("ensure() is deprecated, use update()")
+        std::pair<iterator, bool> ensure( K const& key )
+        {
+            return update( key );
+        }
+        //@endcond
 
-#   ifdef CDS_EMPLACE_SUPPORT
         /// Inserts data of type \ref mapped_type constructed with <tt>std::forward<Args>(args)...</tt>
         /**
             Returns an iterator pointed to inserted value, or \p end() if inserting is failed
-
-            This function is available only for compiler that supports
-            variadic template and move semantics
         */
         template <typename K, typename... Args>
         iterator emplace( K&& key, Args&&... args )
         {
             return node_to_iterator( emplace_at( head(), std::forward<K>(key), std::forward<Args>(args)... ));
         }
-#   endif
-
-        /// Find the key \p key
-        /** \anchor cds_nonintrusive_MichaelKVList_nogc_find
 
+        /// 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
+            and returns an iterator pointed to item found and \ref end() otherwise
         */
         template <typename Q>
-        iterator find( Q const& key )
+        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 contains( key );
+        }
+        //@endcond
 
-        /// Finds the key \p val using \p pred predicate for searching
+        /// Checks whether the list contains \p key using \p pred predicate for searching
         /**
-            The function is an analog of \ref cds_nonintrusive_MichaelKVList_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.
         */
         template <typename Q, typename Less>
+        iterator 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>
+        CDS_DEPRECATED("deprecated, use contains()")
         iterator 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
 
         /// Check if the list is empty
         bool empty() const
@@ -493,21 +486,24 @@ 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 item counter provided by \p Traits. 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
-            is empty. To check list emptyness use \ref empty() method.
+            @note Even if you use real item counter and it returns 0, this fact does not mean that the list
+            is empty. To check list emptyness use \p empty() method.
         */
         size_t size() const
         {
             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();
@@ -537,44 +533,38 @@ namespace cds { namespace container {
         }
 
         template <typename K, typename Func>
-        node_type * insert_key_at( head_type& refHead, const K& key, Func f )
+        node_type * insert_with_at( head_type& refHead, const K& key, Func f )
         {
             scoped_node_ptr pNode( alloc_node( key ));
 
             if ( base_class::insert_at( refHead, *pNode )) {
-                cds::unref(f)( pNode->m_Data );
+                f( pNode->m_Data );
                 return pNode.release();
             }
             return nullptr;
         }
 
         template <typename K>
-        std::pair< node_type *, bool > ensure_at( head_type& refHead, const K& key )
+        std::pair< node_type *, bool > update_at( head_type& refHead, const K& key, bool bAllowInsert )
         {
             scoped_node_ptr pNode( alloc_node( key ));
             node_type * pItemFound = nullptr;
 
-#       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 != nullptr );
+            std::pair<bool, bool> ret = base_class::update_at( refHead, *pNode,
+
+                [&pItemFound](bool, node_type& item, node_type&){ pItemFound = &item; },
+                bAllowInsert );
 
-            if ( ret.first && ret.second )
+            if ( ret.second )
                 pNode.release();
             return std::make_pair( pItemFound, ret.second );
         }
 
-#   ifdef CDS_EMPLACE_SUPPORT
         template <typename K, typename... Args>
         node_type * emplace_at( head_type& refHead, K&& key, Args&&... args )
         {
             return insert_node_at( refHead, alloc_node( std::forward<K>(key), std::forward<Args>(args)... ));
         }
-#endif
 
         template <typename K, typename Compare>
         node_type * find_at( head_type& refHead, K const& key, Compare cmp )
@@ -582,21 +572,48 @@ namespace cds { namespace container {
             return base_class::find_at( refHead, key, cmp );
         }
 
-        /*
-        template <typename K, typename Compare typename Func>
-        bool find_at( head_type& refHead, K& key, Compare cmp, Func f )
+        template <typename K>
+        static node_type * alloc_node( const K& key )
         {
-#       ifdef CDS_CXX11_LAMBDA_SUPPORT
-            return base_class::find_at( refHead, key, cmp, [&f]( node_type& node, K const& ){ cds::unref(f)( node.m_Data ); });
-#       else
-            find_functor<Func>  wrapper( f );
-            return base_class::find_at( refHead, key, cmp, cds::ref(wrapper) );
-#       endif
+            return cxx_allocator().New( key );
+        }
+
+        template <typename K, typename V>
+        static node_type * alloc_node( const K& key, const V& val )
+        {
+            return cxx_allocator().New( key, val );
+        }
+
+        template <typename K, typename... Args>
+        static node_type * alloc_node( K&& key, Args&&... args )
+        {
+            return cxx_allocator().MoveNew( std::forward<K>( key ), std::forward<Args>( args )... );
+        }
+
+        static void free_node( node_type * pNode )
+        {
+            cxx_allocator().Delete( pNode );
+        }
+
+        head_type& head()
+        {
+            return base_class::m_pHead;
+        }
+
+        head_type const& head() const
+        {
+            return base_class::m_pHead;
+        }
+
+        iterator node_to_iterator( node_type * pNode )
+        {
+            if ( pNode )
+                return iterator( *pNode );
+            return end();
         }
-        */
         //@endcond
     };
 
 }} // namespace cds::container
 
-#endif // #ifndef __CDS_CONTAINER_MICHAEL_KVLIST_NOGC_H
+#endif // #ifndef CDSLIB_CONTAINER_MICHAEL_KVLIST_NOGC_H