Extending intrusive MichaelSet<HP> to IterableList
[libcds.git] / cds / intrusive / michael_set.h
1 /*
2     This file is a part of libcds - Concurrent Data Structures library
3
4     (C) Copyright Maxim Khizhinsky (libcds.dev@gmail.com) 2006-2016
5
6     Source code repo: http://github.com/khizmax/libcds/
7     Download: http://sourceforge.net/projects/libcds/files/
8     
9     Redistribution and use in source and binary forms, with or without
10     modification, are permitted provided that the following conditions are met:
11
12     * Redistributions of source code must retain the above copyright notice, this
13       list of conditions and the following disclaimer.
14
15     * Redistributions in binary form must reproduce the above copyright notice,
16       this list of conditions and the following disclaimer in the documentation
17       and/or other materials provided with the distribution.
18
19     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20     AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21     IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22     DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23     FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24     DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25     SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26     CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27     OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28     OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31 #ifndef CDSLIB_INTRUSIVE_MICHAEL_SET_H
32 #define CDSLIB_INTRUSIVE_MICHAEL_SET_H
33
34 #include <cds/intrusive/details/michael_set_base.h>
35 #include <cds/intrusive/details/iterable_list_base.h>
36
37 namespace cds { namespace intrusive {
38
39     /// Michael's hash set
40     /** @ingroup cds_intrusive_map
41         \anchor cds_intrusive_MichaelHashSet_hp
42
43         Source:
44             - [2002] Maged Michael "High performance dynamic lock-free hash tables and list-based sets"
45
46         Michael's hash table algorithm is based on lock-free ordered list and it is very simple.
47         The main structure is an array \p T of size \p M. Each element in \p T is basically a pointer
48         to a hash bucket, implemented as a singly linked list. The array of buckets cannot be dynamically expanded.
49         However, each bucket may contain unbounded number of items.
50
51         Template parameters are:
52         - \p GC - Garbage collector used. Note the \p GC must be the same as the GC used for \p OrderedList
53         - \p OrderedList - ordered list implementation used as bucket for hash set, for example, \p MichaelList, \p LazyList, \p IterableList.
54             The intrusive ordered list implementation specifies the type \p T stored in the hash-set, the reclamation
55             schema \p GC used by hash-set, the comparison functor for the type \p T and other features specific for
56             the ordered list.
57         - \p Traits - type traits. See \p michael_set::traits for explanation.
58             Instead of defining \p Traits struct you can use option-based syntax with \p michael_set::make_traits metafunction.
59
60         There are several specializations of \p %MichaelHashSet for each GC. You should include:
61         - <tt><cds/intrusive/michael_set_rcu.h></tt> for \ref cds_intrusive_MichaelHashSet_rcu "RCU type"
62         - <tt><cds/intrusive/michael_set_nogc.h></tt> for \ref cds_intrusive_MichaelHashSet_nogc for append-only set
63         - <tt><cds/intrusive/michael_set.h></tt> for \p gc::HP, \p gc::DHP
64
65         <b>Hash functor</b>
66
67         Some member functions of Michael's hash set accept the key parameter of type \p Q which differs from \p value_type.
68         It is expected that type \p Q contains full key of \p value_type, and for equal keys of type \p Q and \p value_type
69         the hash values of these keys must be equal.
70         The hash functor \p Traits::hash should accept parameters of both type:
71         \code
72         // Our node type
73         struct Foo {
74             std::string key_; // key field
75             // ... other fields
76         };
77
78         // Hash functor
79         struct fooHash {
80             size_t operator()( const std::string& s ) const
81             {
82                 return std::hash( s );
83             }
84
85             size_t operator()( const Foo& f ) const
86             {
87                 return (*this)( f.key_ );
88             }
89         };
90         \endcode
91
92         <b>How to use</b>
93
94         First, you should define ordered list type to use in your hash set:
95         \code
96         // For gc::HP-based MichaelList implementation
97         #include <cds/intrusive/michael_list_hp.h>
98
99         // cds::intrusive::MichaelHashSet declaration
100         #include <cds/intrusive/michael_set.h>
101
102         // Type of hash-set items
103         struct Foo: public cds::intrusive::michael_list::node< cds::gc::HP >
104         {
105             std::string     key_    ;   // key field
106             unsigned        val_    ;   // value field
107             // ...  other value fields
108         };
109
110         // Declare comparator for the item
111         struct FooCmp
112         {
113             int operator()( const Foo& f1, const Foo& f2 ) const
114             {
115                 return f1.key_.compare( f2.key_ );
116             }
117         };
118
119         // Declare bucket type for Michael's hash set
120         // The bucket type is any ordered list type like MichaelList, LazyList
121         typedef cds::intrusive::MichaelList< cds::gc::HP, Foo,
122             typename cds::intrusive::michael_list::make_traits<
123                 // hook option
124                 cds::intrusive::opt::hook< cds::intrusive::michael_list::base_hook< cds::opt::gc< cds::gc::HP > > >
125                 // item comparator option
126                 ,cds::opt::compare< FooCmp >
127             >::type
128         >  Foo_bucket;
129         \endcode
130
131         Second, you should declare Michael's hash set container:
132         \code
133
134         // Declare hash functor
135         // Note, the hash functor accepts parameter type Foo and std::string
136         struct FooHash {
137             size_t operator()( const Foo& f ) const
138             {
139                 return cds::opt::v::hash<std::string>()( f.key_ );
140             }
141             size_t operator()( const std::string& f ) const
142             {
143                 return cds::opt::v::hash<std::string>()( f );
144             }
145         };
146
147         // Michael's set typedef
148         typedef cds::intrusive::MichaelHashSet<
149             cds::gc::HP
150             ,Foo_bucket
151             ,typename cds::intrusive::michael_set::make_traits<
152                 cds::opt::hash< FooHash >
153             >::type
154         > Foo_set;
155         \endcode
156
157         Now, you can use \p Foo_set in your application.
158
159         Like other intrusive containers, you may build several containers on single item structure:
160         \code
161         #include <cds/intrusive/michael_list_hp.h>
162         #include <cds/intrusive/michael_list_dhp.h>
163         #include <cds/intrusive/michael_set.h>
164
165         struct tag_key1_idx;
166         struct tag_key2_idx;
167
168         // Your two-key data
169         // The first key is maintained by gc::HP, second key is maintained by gc::DHP garbage collectors
170         // (I don't know what is needed for, but it is correct)
171         struct Foo
172             : public cds::intrusive::michael_list::node< cds::gc::HP, tag_key1_idx >
173             , public cds::intrusive::michael_list::node< cds::gc::DHP, tag_key2_idx >
174         {
175             std::string     key1_   ;   // first key field
176             unsigned int    key2_   ;   // second key field
177
178             // ... value fields and fields for controlling item's lifetime
179         };
180
181         // Declare comparators for the item
182         struct Key1Cmp
183         {
184             int operator()( const Foo& f1, const Foo& f2 ) const { return f1.key1_.compare( f2.key1_ ) ; }
185         };
186         struct Key2Less
187         {
188             bool operator()( const Foo& f1, const Foo& f2 ) const { return f1.key2_ < f2.key1_ ; }
189         };
190
191         // Declare bucket type for Michael's hash set indexed by key1_ field and maintained by gc::HP
192         typedef cds::intrusive::MichaelList< cds::gc::HP, Foo,
193             typename cds::intrusive::michael_list::make_traits<
194                 // hook option
195                 cds::intrusive::opt::hook< cds::intrusive::michael_list::base_hook< cds::opt::gc< cds::gc::HP >, tag_key1_idx > >
196                 // item comparator option
197                 ,cds::opt::compare< Key1Cmp >
198             >::type
199         >  Key1_bucket;
200
201         // Declare bucket type for Michael's hash set indexed by key2_ field and maintained by gc::DHP
202         typedef cds::intrusive::MichaelList< cds::gc::DHP, Foo,
203             typename cds::intrusive::michael_list::make_traits<
204                 // hook option
205                 cds::intrusive::opt::hook< cds::intrusive::michael_list::base_hook< cds::opt::gc< cds::gc::DHP >, tag_key2_idx > >
206                 // item comparator option
207                 ,cds::opt::less< Key2Less >
208             >::type
209         >  Key2_bucket;
210
211         // Declare hash functor
212         struct Key1Hash {
213             size_t operator()( const Foo& f ) const { return cds::opt::v::hash<std::string>()( f.key1_ ) ; }
214             size_t operator()( const std::string& s ) const { return cds::opt::v::hash<std::string>()( s ) ; }
215         };
216         inline size_t Key2Hash( const Foo& f ) { return (size_t) f.key2_  ; }
217
218         // Michael's set indexed by key1_ field
219         typedef cds::intrusive::MichaelHashSet<
220             cds::gc::HP
221             ,Key1_bucket
222             ,typename cds::intrusive::michael_set::make_traits<
223                 cds::opt::hash< Key1Hash >
224             >::type
225         > key1_set;
226
227         // Michael's set indexed by key2_ field
228         typedef cds::intrusive::MichaelHashSet<
229             cds::gc::DHP
230             ,Key2_bucket
231             ,typename cds::intrusive::michael_set::make_traits<
232                 cds::opt::hash< Key2Hash >
233             >::type
234         > key2_set;
235         \endcode
236     */
237     template <
238         class GC,
239         class OrderedList,
240 #ifdef CDS_DOXYGEN_INVOKED
241         class Traits = michael_set::traits
242 #else
243         class Traits
244 #endif
245     >
246     class MichaelHashSet
247     {
248     public:
249         typedef GC           gc;            ///< Garbage collector
250         typedef OrderedList  ordered_list;  ///< type of ordered list used as a bucket implementation
251         typedef Traits       traits;        ///< Set traits
252
253         typedef typename ordered_list::value_type       value_type      ; ///< type of value to be stored in the set
254         typedef typename ordered_list::key_comparator   key_comparator  ; ///< key comparing functor
255         typedef typename ordered_list::disposer         disposer        ; ///< Node disposer functor
256         typedef typename ordered_list::stat             stat            ; ///< Internal statistics
257
258         /// Hash functor for \p value_type and all its derivatives that you use
259         typedef typename cds::opt::v::hash_selector< typename traits::hash >::type hash;
260         typedef typename traits::item_counter item_counter;   ///< Item counter type
261         typedef typename traits::allocator    allocator;      ///< Bucket table allocator
262
263         typedef typename ordered_list::guarded_ptr guarded_ptr; ///< Guarded pointer
264
265         /// Count of hazard pointer required for the algorithm
266         static CDS_CONSTEXPR const size_t c_nHazardPtrCount = ordered_list::c_nHazardPtrCount;
267
268         // GC and OrderedList::gc must be the same
269         static_assert(std::is_same<gc, typename ordered_list::gc>::value, "GC and OrderedList::gc must be the same");
270
271         // atomicity::empty_item_counter is not allowed as a item counter
272         static_assert(!std::is_same<item_counter, atomicity::empty_item_counter>::value,
273             "cds::atomicity::empty_item_counter is not allowed as a item counter");
274
275     protected:
276         //@cond
277         typedef typename ordered_list::template select_stat_wrapper< typename ordered_list::stat > bucket_stat;
278
279         typedef typename ordered_list::template rebind_traits<
280             cds::opt::item_counter< cds::atomicity::empty_item_counter >
281             , cds::opt::stat< typename bucket_stat::wrapped_stat >
282         >::type internal_bucket_type;
283
284         typedef typename allocator::template rebind< internal_bucket_type >::other bucket_table_allocator;
285
286         hash                        m_HashFunctor;   ///< Hash functor
287         size_t const                m_nHashBitmask;
288         internal_bucket_type*       m_Buckets;       ///< bucket table
289         item_counter                m_ItemCounter;   ///< Item counter
290         typename bucket_stat::stat  m_Stat;          ///< Internal statistics
291         //@endcond
292
293     public:
294     ///@name Forward iterators
295     //@{
296         /// Forward iterator
297         /**
298             The forward iterator for Michael's set is based on \p OrderedList forward iterator and has some features:
299             - it has no post-increment operator
300             - it iterates items in unordered fashion
301             - The iterator cannot be moved across thread boundary because it may contain GC's guard that is thread-private GC data.
302
303             Iterator thread safety depends on type of \p OrderedList:
304             - for \p MichaelList and \p LazyList: iterator guarantees safety even if you delete the item that iterator points to
305               because that item is guarded by hazard pointer.
306               However, in case of concurrent deleting operations it is no guarantee that you iterate all item in the set.
307               Moreover, a crash is possible when you try to iterate the next element that has been deleted by concurrent thread.
308               Use this iterator on the concurrent container for debugging purpose only.
309             - for \p IterableList: iterator is thread-safe. You may use it freely in concurrent environment.
310               
311         */
312         typedef michael_set::details::iterator< internal_bucket_type, false > iterator;
313
314         /// Const forward iterator
315         /**
316             For iterator's features and requirements see \ref iterator
317         */
318         typedef michael_set::details::iterator< internal_bucket_type, true > const_iterator;
319
320         /// Returns a forward iterator addressing the first element in a set
321         /**
322             For empty set \code begin() == end() \endcode
323         */
324         iterator begin()
325         {
326             return iterator( m_Buckets[0].begin(), bucket_begin(), bucket_end() );
327         }
328
329         /// Returns an iterator that addresses the location succeeding the last element in a set
330         /**
331             Do not use the value returned by <tt>end</tt> function to access any item.
332             The returned value can be used only to control reaching the end of the set.
333             For empty set \code begin() == end() \endcode
334         */
335         iterator end()
336         {
337             return iterator( bucket_end()[-1].end(), bucket_end() - 1, bucket_end() );
338         }
339
340         /// Returns a forward const iterator addressing the first element in a set
341         const_iterator begin() const
342         {
343             return get_const_begin();
344         }
345
346         /// Returns a forward const iterator addressing the first element in a set
347         const_iterator cbegin() const
348         {
349             return get_const_begin();
350         }
351
352         /// Returns an const iterator that addresses the location succeeding the last element in a set
353         const_iterator end() const
354         {
355             return get_const_end();
356         }
357
358         /// Returns an const iterator that addresses the location succeeding the last element in a set
359         const_iterator cend() const
360         {
361             return get_const_end();
362         }
363     //@}
364
365     public:
366         /// Initializes hash set
367         /** @anchor cds_intrusive_MichaelHashSet_hp_ctor
368             The Michael's hash set is an unbounded container, but its hash table is non-expandable.
369             At construction time you should pass estimated maximum item count and a load factor.
370             The load factor is average size of one bucket - a small number between 1 and 10.
371             The bucket is an ordered single-linked list, searching in the bucket has linear complexity <tt>O(nLoadFactor)</tt>.
372             The constructor defines hash table size as rounding <tt>nMaxItemCount / nLoadFactor</tt> up to nearest power of two.
373         */
374         MichaelHashSet(
375             size_t nMaxItemCount,   ///< estimation of max item count in the hash set
376             size_t nLoadFactor      ///< load factor: estimation of max number of items in the bucket. Small integer up to 10.
377         ) : m_nHashBitmask( michael_set::details::init_hash_bitmask( nMaxItemCount, nLoadFactor ))
378           , m_Buckets( bucket_table_allocator().allocate( bucket_count()))
379         {
380             for ( auto it = m_Buckets, itEnd = m_Buckets + bucket_count(); it != itEnd; ++it )
381                 construct_bucket<bucket_stat>( it );
382         }
383
384         /// Clears hash set object and destroys it
385         ~MichaelHashSet()
386         {
387             clear();
388
389             for ( auto it = m_Buckets, itEnd = m_Buckets + bucket_count(); it != itEnd; ++it )
390                 it->~internal_bucket_type();
391             bucket_table_allocator().deallocate( m_Buckets, bucket_count() );
392         }
393
394         /// Inserts new node
395         /**
396             The function inserts \p val in the set if it does not contain
397             an item with key equal to \p val.
398
399             Returns \p true if \p val is placed into the set, \p false otherwise.
400         */
401         bool insert( value_type& val )
402         {
403             bool bRet = bucket( val ).insert( val );
404             if ( bRet )
405                 ++m_ItemCounter;
406             return bRet;
407         }
408
409         /// Inserts new node
410         /**
411             This function is intended for derived non-intrusive containers.
412
413             The function allows to split creating of new item into two part:
414             - create item with key only
415             - insert new item into the set
416             - if inserting is success, calls  \p f functor to initialize value-field of \p val.
417
418             The functor signature is:
419             \code
420                 void func( value_type& val );
421             \endcode
422             where \p val is the item inserted.
423
424             The user-defined functor is called only if the inserting is success.
425
426             @warning For \ref cds_intrusive_MichaelList_hp "MichaelList" as the bucket see \ref cds_intrusive_item_creating "insert item troubleshooting".
427             \ref cds_intrusive_LazyList_hp "LazyList" provides exclusive access to inserted item and does not require any node-level
428             synchronization.
429         */
430         template <typename Func>
431         bool insert( value_type& val, Func f )
432         {
433             bool bRet = bucket( val ).insert( val, f );
434             if ( bRet )
435                 ++m_ItemCounter;
436             return bRet;
437         }
438
439         /// Updates the element
440         /**
441             The operation performs inserting or changing data with lock-free manner.
442
443             If the item \p val not found in the set, then \p val is inserted iff \p bAllowInsert is \p true.
444             Otherwise, the functor \p func is called with item found.
445
446             The functor signature depends of the type of \p OrderedList:
447
448             <b>for \p MichaelList, \p LazyList</b>
449                 \code
450                     struct functor {
451                         void operator()( bool bNew, value_type& item, value_type& val );
452                     };
453                 \endcode
454                 with arguments:
455                 - \p bNew - \p true if the item has been inserted, \p false otherwise
456                 - \p item - item of the set
457                 - \p val - argument \p val passed into the \p %update() function
458                 If new item has been inserted (i.e. \p bNew is \p true) then \p item and \p val arguments
459                 refers to the same thing.
460
461                 The functor may change non-key fields of the \p item.
462                 @warning For \ref cds_intrusive_MichaelList_hp "MichaelList" as the bucket see \ref cds_intrusive_item_creating "insert item troubleshooting".
463                 \ref cds_intrusive_LazyList_hp "LazyList" provides exclusive access to inserted item and does not require any node-level
464                 synchronization.
465
466             <b>for \p IterableList</b>
467                 \code
468                 void func( value_type& val, value_type * old );
469                 \endcode
470                 where
471                 - \p val - argument \p val passed into the \p %update() function
472                 - \p old - old value that will be retired. If new item has been inserted then \p old is \p nullptr.
473
474             Returns <tt> std::pair<bool, bool> </tt> where \p first is \p true if operation is successful,
475             \p second is \p true if new item has been added or \p false if the item with \p key
476             already is in the set.
477         */
478         template <typename Func>
479         std::pair<bool, bool> update( value_type& val, Func func, bool bAllowInsert = true )
480         {
481             std::pair<bool, bool> bRet = bucket( val ).update( val, func, bAllowInsert );
482             if ( bRet.second )
483                 ++m_ItemCounter;
484             return bRet;
485         }
486         //@cond
487         template <typename Func>
488         CDS_DEPRECATED("ensure() is deprecated, use update()")
489         std::pair<bool, bool> ensure( value_type& val, Func func )
490         {
491             return update( val, func, true );
492         }
493         //@endcond
494
495         /// Inserts or updates the node (only for \p IterableList)
496         /**
497             The operation performs inserting or changing data with lock-free manner.
498
499             If the item \p val is not found in the set, then \p val is inserted iff \p bAllowInsert is \p true.
500             Otherwise, the current element is changed to \p val, the old element will be retired later
501             by call \p Traits::disposer.
502
503             Returns std::pair<bool, bool> where \p first is \p true if operation is successful,
504             \p second is \p true if \p val has been added or \p false if the item with that key
505             already in the set.
506         */
507 #ifdef CDS_DOXYGEN_INVOKED
508         std::pair<bool, bool> upsert( value_type& val, bool bAllowInsert = true )
509 #else
510         template <typename Q>
511         typename std::enable_if< 
512             std::is_same< Q, value_type>::value && is_iterable_list< ordered_list >::value,
513             std::pair<bool, bool>
514         >::type
515         upsert( Q& val, bool bAllowInsert = true )
516 #endif
517         {
518             std::pair<bool, bool> bRet = bucket( val ).upsert( val, bAllowInsert );
519             if ( bRet.second )
520                 ++m_ItemCounter;
521             return bRet;
522         }
523
524         /// Unlinks the item \p val from the set
525         /**
526             The function searches the item \p val in the set and unlink it
527             if it is found and is equal to \p val.
528
529             The function returns \p true if success and \p false otherwise.
530         */
531         bool unlink( value_type& val )
532         {
533             bool bRet = bucket( val ).unlink( val );
534             if ( bRet )
535                 --m_ItemCounter;
536             return bRet;
537         }
538
539         /// Deletes the item from the set
540         /** \anchor cds_intrusive_MichaelHashSet_hp_erase
541             The function searches an item with key equal to \p key in the set,
542             unlinks it, and returns \p true.
543             If the item with key equal to \p key is not found the function return \p false.
544
545             Note the hash functor should accept a parameter of type \p Q that can be not the same as \p value_type.
546         */
547         template <typename Q>
548         bool erase( Q const& key )
549         {
550             if ( bucket( key ).erase( key )) {
551                 --m_ItemCounter;
552                 return true;
553             }
554             return false;
555         }
556
557         /// Deletes the item from the set using \p pred predicate for searching
558         /**
559             The function is an analog of \ref cds_intrusive_MichaelHashSet_hp_erase "erase(Q const&)"
560             but \p pred is used for key comparing.
561             \p Less functor has the interface like \p std::less.
562             \p pred must imply the same element order as the comparator used for building the set.
563         */
564         template <typename Q, typename Less>
565         bool erase_with( Q const& key, Less pred )
566         {
567             if ( bucket( key ).erase_with( key, pred )) {
568                 --m_ItemCounter;
569                 return true;
570             }
571             return false;
572         }
573
574         /// Deletes the item from the set
575         /** \anchor cds_intrusive_MichaelHashSet_hp_erase_func
576             The function searches an item with key equal to \p key in the set,
577             call \p f functor with item found, and unlinks it from the set.
578             The \ref disposer specified in \p OrderedList class template parameter is called
579             by garbage collector \p GC asynchronously.
580
581             The \p Func interface is
582             \code
583             struct functor {
584                 void operator()( value_type const& item );
585             };
586             \endcode
587
588             If the item with key equal to \p key is not found the function return \p false.
589
590             Note the hash functor should accept a parameter of type \p Q that can be not the same as \p value_type.
591         */
592         template <typename Q, typename Func>
593         bool erase( Q const& key, Func f )
594         {
595             if ( bucket( key ).erase( key, f )) {
596                 --m_ItemCounter;
597                 return true;
598             }
599             return false;
600         }
601
602         /// Deletes the item from the set using \p pred predicate for searching
603         /**
604             The function is an analog of \ref cds_intrusive_MichaelHashSet_hp_erase_func "erase(Q const&, Func)"
605             but \p pred is used for key comparing.
606             \p Less functor has the interface like \p std::less.
607             \p pred must imply the same element order as the comparator used for building the set.
608         */
609         template <typename Q, typename Less, typename Func>
610         bool erase_with( Q const& key, Less pred, Func f )
611         {
612             if ( bucket( key ).erase_with( key, pred, f )) {
613                 --m_ItemCounter;
614                 return true;
615             }
616             return false;
617         }
618
619         /// Extracts the item with specified \p key
620         /** \anchor cds_intrusive_MichaelHashSet_hp_extract
621             The function searches an item with key equal to \p key,
622             unlinks it from the set, and returns an guarded pointer to the item extracted.
623             If \p key is not found the function returns an empty guarded pointer.
624
625             Note the compare functor should accept a parameter of type \p Q that may be not the same as \p value_type.
626
627             The \p disposer specified in \p OrderedList class' template parameter is called automatically
628             by garbage collector \p GC when returned \ref guarded_ptr object will be destroyed or released.
629             @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
630
631             Usage:
632             \code
633             typedef cds::intrusive::MichaelHashSet< your_template_args > michael_set;
634             michael_set theSet;
635             // ...
636             {
637                 michael_set::guarded_ptr gp( theSet.extract( 5 ));
638                 if ( gp ) {
639                     // Deal with gp
640                     // ...
641                 }
642                 // Destructor of gp releases internal HP guard
643             }
644             \endcode
645         */
646         template <typename Q>
647         guarded_ptr extract( Q const& key )
648         {
649             guarded_ptr gp = bucket( key ).extract( key );
650             if ( gp )
651                 --m_ItemCounter;
652             return gp;
653         }
654
655         /// Extracts the item using compare functor \p pred
656         /**
657             The function is an analog of \ref cds_intrusive_MichaelHashSet_hp_extract "extract(Q const&)"
658             but \p pred predicate is used for key comparing.
659
660             \p Less functor has the semantics like \p std::less but should take arguments of type \ref value_type and \p Q
661             in any order.
662             \p pred must imply the same element order as the comparator used for building the list.
663         */
664         template <typename Q, typename Less>
665         guarded_ptr extract_with( Q const& key, Less pred )
666         {
667             guarded_ptr gp = bucket( key ).extract_with( key, pred );
668             if ( gp )
669                 --m_ItemCounter;
670             return gp;
671         }
672
673         /// Finds the key \p key
674         /** \anchor cds_intrusive_MichaelHashSet_hp_find_func
675             The function searches the item with key equal to \p key and calls the functor \p f for item found.
676             The interface of \p Func functor is:
677             \code
678             struct functor {
679                 void operator()( value_type& item, Q& key );
680             };
681             \endcode
682             where \p item is the item found, \p key is the <tt>find</tt> function argument.
683
684             The functor may change non-key fields of \p item. Note that the functor is only guarantee
685             that \p item cannot be disposed during functor is executing.
686             The functor does not serialize simultaneous access to the set \p item. If such access is
687             possible you must provide your own synchronization schema on item level to exclude unsafe item modifications.
688
689             The \p key argument is non-const since it can be used as \p f functor destination i.e., the functor
690             may modify both arguments.
691
692             Note the hash functor specified for class \p Traits template parameter
693             should accept a parameter of type \p Q that can be not the same as \p value_type.
694
695             The function returns \p true if \p key is found, \p false otherwise.
696         */
697         template <typename Q, typename Func>
698         bool find( Q& key, Func f )
699         {
700             return bucket( key ).find( key, f );
701         }
702         //@cond
703         template <typename Q, typename Func>
704         bool find( Q const& key, Func f )
705         {
706             return bucket( key ).find( key, f );
707         }
708         //@endcond
709
710         /// Finds \p key and returns iterator pointed to the item found (only for \p IterableList)
711         /**
712             If \p key is not found the function returns \p end().
713
714             @note This function is supported only for the set based on \p IterableList
715         */
716         template <typename Q>
717 #ifdef CDS_DOXYGEN_INVOKED
718         iterator
719 #else
720         typename std::enable_if< std::is_same<Q,Q>::value && is_iterable_list< ordered_list >::value, iterator >::type
721 #endif
722         find( Q& key )
723         {
724             internal_bucket_type& b = bucket( key );
725             typename internal_bucket_type::iterator it = b.find( key );
726             if ( it == b.end() )
727                 return end();
728             return iterator( it, &b, bucket_end());
729         }
730         //@cond
731         template <typename Q>
732         typename std::enable_if< std::is_same<Q, Q>::value && is_iterable_list< ordered_list >::value, iterator >::type
733         find( Q const& key )
734         {
735             internal_bucket_type& b = bucket( key );
736             typename internal_bucket_type::iterator it = b.find( key );
737             if ( it == b.end() )
738                 return end();
739             return iterator( it, &b, bucket_end() );
740         }
741         //@endcond
742
743
744         /// Finds the key \p key using \p pred predicate for searching
745         /**
746             The function is an analog of \ref cds_intrusive_MichaelHashSet_hp_find_func "find(Q&, Func)"
747             but \p pred is used for key comparing.
748             \p Less functor has the interface like \p std::less.
749             \p pred must imply the same element order as the comparator used for building the set.
750         */
751         template <typename Q, typename Less, typename Func>
752         bool find_with( Q& key, Less pred, Func f )
753         {
754             return bucket( key ).find_with( key, pred, f );
755         }
756         //@cond
757         template <typename Q, typename Less, typename Func>
758         bool find_with( Q const& key, Less pred, Func f )
759         {
760             return bucket( key ).find_with( key, pred, f );
761         }
762         //@endcond
763
764         /// Finds \p key using \p pred predicate and returns iterator pointed to the item found (only for \p IterableList)
765         /**
766             The function is an analog of \p find(Q&) but \p pred is used for key comparing.
767             \p Less functor has the interface like \p std::less.
768             \p pred must imply the same element order as the comparator used for building the set.
769
770             If \p key is not found the function returns \p end().
771
772             @note This function is supported only for the set based on \p IterableList
773         */
774         template <typename Q, typename Less>
775 #ifdef CDS_DOXYGEN_INVOKED
776         iterator
777 #else
778         typename std::enable_if< std::is_same<Q, Q>::value && is_iterable_list< ordered_list >::value, iterator >::type
779 #endif
780         find_with( Q& key, Less pred )
781         {
782             internal_bucket_type& b = bucket( key );
783             typename internal_bucket_type::iterator it = b.find_with( key, pred );
784             if ( it == b.end() )
785                 return end();
786             return iterator( it, &b, bucket_end() );
787         }
788         //@cond
789         template <typename Q, typename Less>
790         typename std::enable_if< std::is_same<Q, Q>::value && is_iterable_list< ordered_list >::value, iterator >::type
791         find_with( Q const& key, Less pred )
792         {
793             internal_bucket_type& b = bucket( key );
794             typename internal_bucket_type::iterator it = b.find_with( key, pred );
795             if ( it == b.end() )
796                 return end();
797             return iterator( it, &b, bucket_end() );
798         }
799         //@endcond
800
801         /// Checks whether the set contains \p key
802         /**
803
804             The function searches the item with key equal to \p key
805             and returns \p true if the key is found, and \p false otherwise.
806
807             Note the hash functor specified for class \p Traits template parameter
808             should accept a parameter of type \p Q that can be not the same as \p value_type.
809         */
810         template <typename Q>
811         bool contains( Q const& key )
812         {
813             return bucket( key ).contains( key );
814         }
815
816         /// Checks whether the set contains \p key using \p pred predicate for searching
817         /**
818             The function is an analog of <tt>contains( key )</tt> but \p pred is used for key comparing.
819             \p Less functor has the interface like \p std::less.
820             \p Less must imply the same element order as the comparator used for building the set.
821         */
822         template <typename Q, typename Less>
823         bool contains( Q const& key, Less pred )
824         {
825             return bucket( key ).contains( key, pred );
826         }
827
828         /// Finds the key \p key and return the item found
829         /** \anchor cds_intrusive_MichaelHashSet_hp_get
830             The function searches the item with key equal to \p key
831             and returns the guarded pointer to the item found.
832             If \p key is not found the function returns an empty \p guarded_ptr.
833
834             @note Each \p guarded_ptr object uses one GC's guard which can be limited resource.
835
836             Usage:
837             \code
838             typedef cds::intrusive::MichaelHashSet< your_template_params >  michael_set;
839             michael_set theSet;
840             // ...
841             {
842                 michael_set::guarded_ptr gp( theSet.get( 5 ));
843                 if ( theSet.get( 5 )) {
844                     // Deal with gp
845                     //...
846                 }
847                 // Destructor of guarded_ptr releases internal HP guard
848             }
849             \endcode
850
851             Note the compare functor specified for \p OrderedList template parameter
852             should accept a parameter of type \p Q that can be not the same as \p value_type.
853         */
854         template <typename Q>
855         guarded_ptr get( Q const& key )
856         {
857             return bucket( key ).get( key );
858         }
859
860         /// Finds the key \p key and return the item found
861         /**
862             The function is an analog of \ref cds_intrusive_MichaelHashSet_hp_get "get( Q const&)"
863             but \p pred is used for comparing the keys.
864
865             \p Less functor has the semantics like \p std::less but should take arguments of type \ref value_type and \p Q
866             in any order.
867             \p pred must imply the same element order as the comparator used for building the set.
868         */
869         template <typename Q, typename Less>
870         guarded_ptr get_with( Q const& key, Less pred )
871         {
872             return bucket( key ).get_with( key, pred );
873         }
874
875         /// Clears the set (non-atomic)
876         /**
877             The function unlink all items from the set.
878             The function is not atomic. It cleans up each bucket and then resets the item counter to zero.
879             If there are a thread that performs insertion while \p %clear() is working the result is undefined in general case:
880             \p empty() may return \p true but the set may contain item(s).
881             Therefore, \p %clear() may be used only for debugging purposes.
882
883             For each item the \p disposer is called after unlinking.
884         */
885         void clear()
886         {
887             for ( size_t i = 0; i < bucket_count(); ++i )
888                 m_Buckets[i].clear();
889             m_ItemCounter.reset();
890         }
891
892         /// Checks if the set is empty
893         /**
894             Emptiness is checked by item counting: if item count is zero then the set is empty.
895             Thus, the correct item counting feature is an important part of Michael's set implementation.
896         */
897         bool empty() const
898         {
899             return size() == 0;
900         }
901
902         /// Returns item count in the set
903         size_t size() const
904         {
905             return m_ItemCounter;
906         }
907
908         /// Returns const reference to internal statistics
909         stat const& statistics() const
910         {
911             return m_Stat;
912         }
913
914         /// Returns the size of hash table
915         /**
916             Since \p %MichaelHashSet cannot dynamically extend the hash table size,
917             the value returned is an constant depending on object initialization parameters,
918             see \p MichaelHashSet::MichaelHashSet.
919         */
920         size_t bucket_count() const
921         {
922             return m_nHashBitmask + 1;
923         }
924
925     private:
926         //@cond
927         internal_bucket_type * bucket_begin() const
928         {
929             return m_Buckets;
930         }
931
932         internal_bucket_type * bucket_end() const
933         {
934             return m_Buckets + bucket_count();
935         }
936
937         const_iterator get_const_begin() const
938         {
939             return const_iterator( m_Buckets[0].cbegin(), bucket_begin(), bucket_end() );
940         }
941         const_iterator get_const_end() const
942         {
943             return const_iterator( bucket_end()[-1].cend(), bucket_end() - 1, bucket_end() );
944         }
945
946         template <typename Stat>
947         typename std::enable_if< Stat::empty >::type construct_bucket( internal_bucket_type * bucket )
948         {
949             new (bucket) internal_bucket_type;
950         }
951
952         template <typename Stat>
953         typename std::enable_if< !Stat::empty >::type construct_bucket( internal_bucket_type * bucket )
954         {
955             new (bucket) internal_bucket_type( m_Stat );
956         }
957
958         /// Calculates hash value of \p key
959         template <typename Q>
960         size_t hash_value( const Q& key ) const
961         {
962             return m_HashFunctor( key ) & m_nHashBitmask;
963         }
964
965         /// Returns the bucket (ordered list) for \p key
966         template <typename Q>
967         internal_bucket_type& bucket( const Q& key )
968         {
969             return m_Buckets[hash_value( key )];
970         }
971         //@endcond
972     };
973
974 }}  // namespace cds::intrusive
975
976 #endif // ifndef CDSLIB_INTRUSIVE_MICHAEL_SET_H