Added copyright and license
[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/details/allocator.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.
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 ordered_list bucket_type;   ///< bucket type
252         typedef Traits       traits;       ///< Set traits
253
254         typedef typename ordered_list::value_type       value_type      ;   ///< type of value to be stored in the set
255         typedef typename ordered_list::key_comparator   key_comparator  ;   ///< key comparing functor
256         typedef typename ordered_list::disposer         disposer        ;   ///< Node disposer functor
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
262         typedef typename ordered_list::guarded_ptr guarded_ptr; ///< Guarded pointer
263
264         /// Bucket table allocator
265         typedef cds::details::Allocator< bucket_type, typename traits::allocator > bucket_table_allocator;
266
267     protected:
268         item_counter    m_ItemCounter;   ///< Item counter
269         hash            m_HashFunctor;   ///< Hash functor
270         bucket_type *   m_Buckets;      ///< bucket table
271
272     private:
273         //@cond
274         const size_t    m_nHashBitmask;
275         //@endcond
276
277     protected:
278         //@cond
279         /// Calculates hash value of \p key
280         template <typename Q>
281         size_t hash_value( const Q& key ) const
282         {
283             return m_HashFunctor( key ) & m_nHashBitmask;
284         }
285
286         /// Returns the bucket (ordered list) for \p key
287         template <typename Q>
288         bucket_type&    bucket( const Q& key )
289         {
290             return m_Buckets[ hash_value( key ) ];
291         }
292         //@endcond
293
294     public:
295         /// Forward iterator
296         /**
297             The forward iterator for Michael's set is based on \p OrderedList forward iterator and has some features:
298             - it has no post-increment operator
299             - it iterates items in unordered fashion
300             - The iterator cannot be moved across thread boundary since it may contain GC's guard that is thread-private GC data.
301             - Iterator ensures thread-safety even if you delete the item that iterator points to. However, in case of concurrent
302               deleting operations it is no guarantee that you iterate all item in the set.
303
304             Therefore, the use of iterators in concurrent environment is not good idea. Use the iterator for the concurrent container
305             for debug purpose only.
306         */
307         typedef michael_set::details::iterator< bucket_type, false >    iterator;
308
309         /// Const forward iterator
310         /**
311             For iterator's features and requirements see \ref iterator
312         */
313         typedef michael_set::details::iterator< bucket_type, true >     const_iterator;
314
315         /// Returns a forward iterator addressing the first element in a set
316         /**
317             For empty set \code begin() == end() \endcode
318         */
319         iterator begin()
320         {
321             return iterator( m_Buckets[0].begin(), m_Buckets, m_Buckets + bucket_count() );
322         }
323
324         /// Returns an iterator that addresses the location succeeding the last element in a set
325         /**
326             Do not use the value returned by <tt>end</tt> function to access any item.
327             The returned value can be used only to control reaching the end of the set.
328             For empty set \code begin() == end() \endcode
329         */
330         iterator end()
331         {
332             return iterator( m_Buckets[bucket_count() - 1].end(), m_Buckets + bucket_count() - 1, m_Buckets + bucket_count() );
333         }
334
335         /// Returns a forward const iterator addressing the first element in a set
336         //@{
337         const_iterator begin() const
338         {
339             return get_const_begin();
340         }
341         const_iterator cbegin() const
342         {
343             return get_const_begin();
344         }
345         //@}
346
347         /// Returns an const iterator that addresses the location succeeding the last element in a set
348         //@{
349         const_iterator end() const
350         {
351             return get_const_end();
352         }
353         const_iterator cend() const
354         {
355             return get_const_end();
356         }
357         //@}
358
359     private:
360         //@cond
361         const_iterator get_const_begin() const
362         {
363             return const_iterator( m_Buckets[0].cbegin(), m_Buckets, m_Buckets + bucket_count() );
364         }
365         const_iterator get_const_end() const
366         {
367             return const_iterator( m_Buckets[bucket_count() - 1].cend(), m_Buckets + bucket_count() - 1, m_Buckets + bucket_count() );
368         }
369         //@endcond
370
371     public:
372         /// Initializes hash set
373         /** @anchor cds_intrusive_MichaelHashSet_hp_ctor
374             The Michael's hash set is an unbounded container, but its hash table is non-expandable.
375             At construction time you should pass estimated maximum item count and a load factor.
376             The load factor is average size of one bucket - a small number between 1 and 10.
377             The bucket is an ordered single-linked list, searching in the bucket has linear complexity <tt>O(nLoadFactor)</tt>.
378             The constructor defines hash table size as rounding <tt>nMaxItemCount / nLoadFactor</tt> up to nearest power of two.
379         */
380         MichaelHashSet(
381             size_t nMaxItemCount,   ///< estimation of max item count in the hash set
382             size_t nLoadFactor      ///< load factor: estimation of max number of items in the bucket. Small integer up to 10.
383         ) : m_nHashBitmask( michael_set::details::init_hash_bitmask( nMaxItemCount, nLoadFactor ))
384         {
385             // GC and OrderedList::gc must be the same
386             static_assert( std::is_same<gc, typename bucket_type::gc>::value, "GC and OrderedList::gc must be the same");
387
388             // atomicity::empty_item_counter is not allowed as a item counter
389             static_assert( !std::is_same<item_counter, atomicity::empty_item_counter>::value,
390                            "cds::atomicity::empty_item_counter is not allowed as a item counter");
391
392             m_Buckets = bucket_table_allocator().NewArray( bucket_count() );
393         }
394
395         /// Clears hash set object and destroys it
396         ~MichaelHashSet()
397         {
398             clear();
399             bucket_table_allocator().Delete( m_Buckets, bucket_count() );
400         }
401
402         /// Inserts new node
403         /**
404             The function inserts \p val in the set if it does not contain
405             an item with key equal to \p val.
406
407             Returns \p true if \p val is placed into the set, \p false otherwise.
408         */
409         bool insert( value_type& val )
410         {
411             bool bRet = bucket( val ).insert( val );
412             if ( bRet )
413                 ++m_ItemCounter;
414             return bRet;
415         }
416
417         /// Inserts new node
418         /**
419             This function is intended for derived non-intrusive containers.
420
421             The function allows to split creating of new item into two part:
422             - create item with key only
423             - insert new item into the set
424             - if inserting is success, calls  \p f functor to initialize value-field of \p val.
425
426             The functor signature is:
427             \code
428                 void func( value_type& val );
429             \endcode
430             where \p val is the item inserted.
431
432             The user-defined functor is called only if the inserting is success.
433
434             @warning For \ref cds_intrusive_MichaelList_hp "MichaelList" as the bucket see \ref cds_intrusive_item_creating "insert item troubleshooting".
435             \ref cds_intrusive_LazyList_hp "LazyList" provides exclusive access to inserted item and does not require any node-level
436             synchronization.
437         */
438         template <typename Func>
439         bool insert( value_type& val, Func f )
440         {
441             bool bRet = bucket( val ).insert( val, f );
442             if ( bRet )
443                 ++m_ItemCounter;
444             return bRet;
445         }
446
447         /// Updates the element
448         /**
449             The operation performs inserting or changing data with lock-free manner.
450
451             If the item \p val not found in the set, then \p val is inserted iff \p bAllowInsert is \p true.
452             Otherwise, the functor \p func is called with item found.
453             The functor signature is:
454             \code
455                 struct functor {
456                     void operator()( bool bNew, value_type& item, value_type& val );
457                 };
458             \endcode
459             with arguments:
460             - \p bNew - \p true if the item has been inserted, \p false otherwise
461             - \p item - item of the set
462             - \p val - argument \p val passed into the \p %update() function
463             If new item has been inserted (i.e. \p bNew is \p true) then \p item and \p val arguments
464             refers to the same thing.
465
466             The functor may change non-key fields of the \p item.
467
468             Returns <tt> std::pair<bool, bool> </tt> where \p first is \p true if operation is successfull,
469             \p second is \p true if new item has been added or \p false if the item with \p key
470             already is in the set.
471
472             @warning For \ref cds_intrusive_MichaelList_hp "MichaelList" as the bucket see \ref cds_intrusive_item_creating "insert item troubleshooting".
473             \ref cds_intrusive_LazyList_hp "LazyList" provides exclusive access to inserted item and does not require any node-level
474             synchronization.
475         */
476         template <typename Func>
477         std::pair<bool, bool> update( value_type& val, Func func, bool bAllowInsert = true )
478         {
479             std::pair<bool, bool> bRet = bucket( val ).update( val, func, bAllowInsert );
480             if ( bRet.second )
481                 ++m_ItemCounter;
482             return bRet;
483         }
484         //@cond
485         template <typename Func>
486         CDS_DEPRECATED("ensure() is deprecated, use update()")
487         std::pair<bool, bool> ensure( value_type& val, Func func )
488         {
489             return update( val, func, true );
490         }
491         //@endcond
492
493         /// Unlinks the item \p val from the set
494         /**
495             The function searches the item \p val in the set and unlink it
496             if it is found and is equal to \p val.
497
498             The function returns \p true if success and \p false otherwise.
499         */
500         bool unlink( value_type& val )
501         {
502             bool bRet = bucket( val ).unlink( val );
503             if ( bRet )
504                 --m_ItemCounter;
505             return bRet;
506         }
507
508         /// Deletes the item from the set
509         /** \anchor cds_intrusive_MichaelHashSet_hp_erase
510             The function searches an item with key equal to \p key in the set,
511             unlinks it, and returns \p true.
512             If the item with key equal to \p key is not found the function return \p false.
513
514             Note the hash functor should accept a parameter of type \p Q that can be not the same as \p value_type.
515         */
516         template <typename Q>
517         bool erase( Q const& key )
518         {
519             if ( bucket( key ).erase( key )) {
520                 --m_ItemCounter;
521                 return true;
522             }
523             return false;
524         }
525
526         /// Deletes the item from the set using \p pred predicate for searching
527         /**
528             The function is an analog of \ref cds_intrusive_MichaelHashSet_hp_erase "erase(Q const&)"
529             but \p pred is used for key comparing.
530             \p Less functor has the interface like \p std::less.
531             \p pred must imply the same element order as the comparator used for building the set.
532         */
533         template <typename Q, typename Less>
534         bool erase_with( Q const& key, Less pred )
535         {
536             if ( bucket( key ).erase_with( key, pred )) {
537                 --m_ItemCounter;
538                 return true;
539             }
540             return false;
541         }
542
543         /// Deletes the item from the set
544         /** \anchor cds_intrusive_MichaelHashSet_hp_erase_func
545             The function searches an item with key equal to \p key in the set,
546             call \p f functor with item found, and unlinks it from the set.
547             The \ref disposer specified in \p OrderedList class template parameter is called
548             by garbage collector \p GC asynchronously.
549
550             The \p Func interface is
551             \code
552             struct functor {
553                 void operator()( value_type const& item );
554             };
555             \endcode
556
557             If the item with key equal to \p key is not found the function return \p false.
558
559             Note the hash functor should accept a parameter of type \p Q that can be not the same as \p value_type.
560         */
561         template <typename Q, typename Func>
562         bool erase( const Q& key, Func f )
563         {
564             if ( bucket( key ).erase( key, f )) {
565                 --m_ItemCounter;
566                 return true;
567             }
568             return false;
569         }
570
571         /// Deletes the item from the set using \p pred predicate for searching
572         /**
573             The function is an analog of \ref cds_intrusive_MichaelHashSet_hp_erase_func "erase(Q const&, Func)"
574             but \p pred is used for key comparing.
575             \p Less functor has the interface like \p std::less.
576             \p pred must imply the same element order as the comparator used for building the set.
577         */
578         template <typename Q, typename Less, typename Func>
579         bool erase_with( const Q& key, Less pred, Func f )
580         {
581             if ( bucket( key ).erase_with( key, pred, f )) {
582                 --m_ItemCounter;
583                 return true;
584             }
585             return false;
586         }
587
588         /// Extracts the item with specified \p key
589         /** \anchor cds_intrusive_MichaelHashSet_hp_extract
590             The function searches an item with key equal to \p key,
591             unlinks it from the set, and returns an guarded pointer to the item extracted.
592             If \p key is not found the function returns an empty guarded pointer.
593
594             Note the compare functor should accept a parameter of type \p Q that may be not the same as \p value_type.
595
596             The \p disposer specified in \p OrderedList class' template parameter is called automatically
597             by garbage collector \p GC when returned \ref guarded_ptr object will be destroyed or released.
598             @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
599
600             Usage:
601             \code
602             typedef cds::intrusive::MichaelHashSet< your_template_args > michael_set;
603             michael_set theSet;
604             // ...
605             {
606                 michael_set::guarded_ptr gp( theSet.extract( 5 ));
607                 if ( gp ) {
608                     // Deal with gp
609                     // ...
610                 }
611                 // Destructor of gp releases internal HP guard
612             }
613             \endcode
614         */
615         template <typename Q>
616         guarded_ptr extract( Q const& key )
617         {
618             guarded_ptr gp = bucket( key ).extract( key );
619             if ( gp )
620                 --m_ItemCounter;
621             return gp;
622         }
623
624         /// Extracts the item using compare functor \p pred
625         /**
626             The function is an analog of \ref cds_intrusive_MichaelHashSet_hp_extract "extract(Q const&)"
627             but \p pred predicate is used for key comparing.
628
629             \p Less functor has the semantics like \p std::less but should take arguments of type \ref value_type and \p Q
630             in any order.
631             \p pred must imply the same element order as the comparator used for building the list.
632         */
633         template <typename Q, typename Less>
634         guarded_ptr extract_with( Q const& key, Less pred )
635         {
636             guarded_ptr gp = bucket( key ).extract_with( key, pred );
637             if ( gp )
638                 --m_ItemCounter;
639             return gp;
640         }
641
642         /// Finds the key \p key
643         /** \anchor cds_intrusive_MichaelHashSet_hp_find_func
644             The function searches the item with key equal to \p key and calls the functor \p f for item found.
645             The interface of \p Func functor is:
646             \code
647             struct functor {
648                 void operator()( value_type& item, Q& key );
649             };
650             \endcode
651             where \p item is the item found, \p key is the <tt>find</tt> function argument.
652
653             The functor may change non-key fields of \p item. Note that the functor is only guarantee
654             that \p item cannot be disposed during functor is executing.
655             The functor does not serialize simultaneous access to the set \p item. If such access is
656             possible you must provide your own synchronization schema on item level to exclude unsafe item modifications.
657
658             The \p key argument is non-const since it can be used as \p f functor destination i.e., the functor
659             may modify both arguments.
660
661             Note the hash functor specified for class \p Traits template parameter
662             should accept a parameter of type \p Q that can be not the same as \p value_type.
663
664             The function returns \p true if \p key is found, \p false otherwise.
665         */
666         template <typename Q, typename Func>
667         bool find( Q& key, Func f )
668         {
669             return bucket( key ).find( key, f );
670         }
671         //@cond
672         template <typename Q, typename Func>
673         bool find( Q const& key, Func f )
674         {
675             return bucket( key ).find( key, f );
676         }
677         //@endcond
678
679         /// Finds the key \p key using \p pred predicate for searching
680         /**
681             The function is an analog of \ref cds_intrusive_MichaelHashSet_hp_find_func "find(Q&, Func)"
682             but \p pred is used for key comparing.
683             \p Less functor has the interface like \p std::less.
684             \p pred must imply the same element order as the comparator used for building the set.
685         */
686         template <typename Q, typename Less, typename Func>
687         bool find_with( Q& key, Less pred, Func f )
688         {
689             return bucket( key ).find_with( key, pred, f );
690         }
691         //@cond
692         template <typename Q, typename Less, typename Func>
693         bool find_with( Q const& key, Less pred, Func f )
694         {
695             return bucket( key ).find_with( key, pred, f );
696         }
697         //@endcond
698
699         /// Checks whether the set contains \p key
700         /**
701
702             The function searches the item with key equal to \p key
703             and returns \p true if the key is found, and \p false otherwise.
704
705             Note the hash functor specified for class \p Traits template parameter
706             should accept a parameter of type \p Q that can be not the same as \p value_type.
707         */
708         template <typename Q>
709         bool contains( Q const& key )
710         {
711             return bucket( key ).contains( key );
712         }
713         //@cond
714         template <typename Q>
715         CDS_DEPRECATED("use contains()")
716         bool find( Q const& key )
717         {
718             return contains( key );
719         }
720         //@endcond
721
722         /// Checks whether the set contains \p key using \p pred predicate for searching
723         /**
724             The function is an analog of <tt>contains( key )</tt> but \p pred is used for key comparing.
725             \p Less functor has the interface like \p std::less.
726             \p Less must imply the same element order as the comparator used for building the set.
727         */
728         template <typename Q, typename Less>
729         bool contains( Q const& key, Less pred )
730         {
731             return bucket( key ).contains( key, pred );
732         }
733         //@cond
734         template <typename Q, typename Less>
735         CDS_DEPRECATED("use contains()")
736         bool find_with( Q const& key, Less pred )
737         {
738             return contains( key, pred );
739         }
740         //@endcond
741
742         /// Finds the key \p key and return the item found
743         /** \anchor cds_intrusive_MichaelHashSet_hp_get
744             The function searches the item with key equal to \p key
745             and returns the guarded pointer to the item found.
746             If \p key is not found the function returns an empty \p guarded_ptr.
747
748             @note Each \p guarded_ptr object uses one GC's guard which can be limited resource.
749
750             Usage:
751             \code
752             typedef cds::intrusive::MichaelHashSet< your_template_params >  michael_set;
753             michael_set theSet;
754             // ...
755             {
756                 michael_set::guarded_ptr gp( theSet.get( 5 ));
757                 if ( theSet.get( 5 )) {
758                     // Deal with gp
759                     //...
760                 }
761                 // Destructor of guarded_ptr releases internal HP guard
762             }
763             \endcode
764
765             Note the compare functor specified for \p OrderedList template parameter
766             should accept a parameter of type \p Q that can be not the same as \p value_type.
767         */
768         template <typename Q>
769         guarded_ptr get( Q const& key )
770         {
771             return bucket( key ).get( key );
772         }
773
774         /// Finds the key \p key and return the item found
775         /**
776             The function is an analog of \ref cds_intrusive_MichaelHashSet_hp_get "get( Q const&)"
777             but \p pred is used for comparing the keys.
778
779             \p Less functor has the semantics like \p std::less but should take arguments of type \ref value_type and \p Q
780             in any order.
781             \p pred must imply the same element order as the comparator used for building the set.
782         */
783         template <typename Q, typename Less>
784         guarded_ptr get_with( Q const& key, Less pred )
785         {
786             return bucket( key ).get_with( key, pred );
787         }
788
789         /// Clears the set (non-atomic)
790         /**
791             The function unlink all items from the set.
792             The function is not atomic. It cleans up each bucket and then resets the item counter to zero.
793             If there are a thread that performs insertion while \p %clear() is working the result is undefined in general case:
794             \p empty() may return \p true but the set may contain item(s).
795             Therefore, \p %clear() may be used only for debugging purposes.
796
797             For each item the \p disposer is called after unlinking.
798         */
799         void clear()
800         {
801             for ( size_t i = 0; i < bucket_count(); ++i )
802                 m_Buckets[i].clear();
803             m_ItemCounter.reset();
804         }
805
806         /// Checks if the set is empty
807         /**
808             Emptiness is checked by item counting: if item count is zero then the set is empty.
809             Thus, the correct item counting feature is an important part of Michael's set implementation.
810         */
811         bool empty() const
812         {
813             return size() == 0;
814         }
815
816         /// Returns item count in the set
817         size_t size() const
818         {
819             return m_ItemCounter;
820         }
821
822         /// Returns the size of hash table
823         /**
824             Since \p %MichaelHashSet cannot dynamically extend the hash table size,
825             the value returned is an constant depending on object initialization parameters,
826             see \p MichaelHashSet::MichaelHashSet.
827         */
828         size_t bucket_count() const
829         {
830             return m_nHashBitmask + 1;
831         }
832     };
833
834 }}  // namespace cds::intrusive
835
836 #endif // ifndef CDSLIB_INTRUSIVE_MICHAEL_SET_H