Updated copyright
[libcds.git] / cds / container / michael_set_rcu.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-2017
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_CONTAINER_MICHAEL_SET_RCU_H
32 #define CDSLIB_CONTAINER_MICHAEL_SET_RCU_H
33
34 #include <cds/container/details/michael_set_base.h>
35 #include <cds/details/allocator.h>
36
37 namespace cds { namespace container {
38
39     /// Michael's hash set (template specialization for \ref cds_urcu_desc "RCU")
40     /** @ingroup cds_nonintrusive_set
41         \anchor cds_nonintrusive_MichaelHashSet_rcu
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 RCU - one of \ref cds_urcu_gc "RCU type"
53         - \p OrderedList - ordered list implementation used as the bucket for hash set, for example,
54             \ref cds_nonintrusive_MichaelList_rcu "MichaelList".
55             The ordered list implementation specifies the type \p T stored in the hash-set,
56             the comparison functor for the type \p T and other features specific for
57             the ordered list.
58         - \p Traits - set traits, default is michael_set::traits.
59             Instead of defining \p Traits struct you may use option-based syntax with michael_set::make_traits metafunction.
60
61         About hash functor see \ref cds_nonintrusive_MichaelHashSet_hash_functor "MichaelSet hash functor".
62
63         <b>How to use</b>
64
65         Suppose, we have the following type \p Foo that we want to store in your \p %MichaelHashSet:
66         \code
67         struct Foo {
68             int     nKey    ;   // key field
69             int     nVal    ;   // value field
70         };
71         \endcode
72
73         To use \p %MichaelHashSet for \p Foo values, you should first choose suitable ordered list class
74         that will be used as a bucket for the set. We will cds::urcu::general_buffered<> RCU type and
75         MichaelList as a bucket type.
76         You should include RCU-related header file (<tt>cds/urcu/general_buffered.h</tt> in this example)
77         before including <tt>cds/container/michael_set_rcu.h</tt>.
78         Also, for ordered list we should develop a comparator for our \p Foo struct.
79         \code
80         #include <cds/urcu/general_buffered.h>
81         #include <cds/container/michael_list_rcu.h>
82         #include <cds/container/michael_set_rcu.h>
83
84         namespace cc = cds::container;
85
86         // Foo comparator
87         struct Foo_cmp {
88             int operator ()(Foo const& v1, Foo const& v2 ) const
89             {
90                 if ( std::less( v1.nKey, v2.nKey ))
91                     return -1;
92                 return std::less(v2.nKey, v1.nKey) ? 1 : 0;
93             }
94         };
95
96         // Ordered list
97         typedef cc::MichaelList< cds::urcu::gc< cds::urcu::general_buffered<> >, Foo,
98             typename cc::michael_list::make_traits<
99                 cc::opt::compare< Foo_cmp >     // item comparator option
100             >::type
101         > bucket_list;
102
103         // Hash functor for Foo
104         struct foo_hash {
105             size_t operator ()( int i ) const
106             {
107                 return std::hash( i );
108             }
109             size_t operator()( Foo const& i ) const
110             {
111                 return std::hash( i.nKey );
112             }
113         };
114
115         // Declare the set
116         // Note that \p RCU template parameter of ordered list must be equal \p RCU for the set.
117         typedef cc::MichaelHashSet< cds::urcu::gc< cds::urcu::general_buffered<> >, bucket_list,
118             cc::michael_set::make_traits<
119                 cc::opt::hash< foo_hash >
120             >::type
121         > foo_set;
122
123         foo_set fooSet;
124         \endcode
125     */
126     template <
127         class RCU,
128         class OrderedList,
129 #ifdef CDS_DOXYGEN_INVOKED
130         class Traits = michael_set::traits
131 #else
132         class Traits
133 #endif
134     >
135     class MichaelHashSet< cds::urcu::gc< RCU >, OrderedList, Traits >
136     {
137     public:
138         typedef cds::urcu::gc< RCU > gc; ///< RCU used as garbage collector
139         typedef OrderedList ordered_list; ///< type of ordered list to be used as a bucket implementation
140         typedef Traits      traits;      ///< Set traits
141
142         typedef typename ordered_list::value_type     value_type;     ///< type of value to be stored in the list
143         typedef typename ordered_list::key_comparator key_comparator; ///< key comparing functor
144 #ifdef CDS_DOXYGEN_INVOKED
145         typedef typename ordered_list::stat       stat;       ///< Internal statistics
146         typedef typename ordered_list::exempt_ptr exempt_ptr; ///< pointer to extracted node
147         typedef typename ordered_list::raw_ptr    raw_ptr;    ///< Return type of \p get() member function and its derivatives
148 #endif
149
150         /// Hash functor for \ref value_type and all its derivatives that you use
151         typedef typename cds::opt::v::hash_selector< typename traits::hash >::type hash;
152         typedef typename traits::item_counter item_counter; ///< Item counter type
153         typedef typename traits::allocator    allocator;    ///< Bucket table allocator
154
155         typedef typename ordered_list::rcu_lock   rcu_lock;   ///< RCU scoped lock
156         /// Group of \p extract_xxx functions require external locking if underlying ordered list requires that
157         static CDS_CONSTEXPR const bool c_bExtractLockExternal = ordered_list::c_bExtractLockExternal;
158
159         // GC and OrderedList::gc must be the same
160         static_assert(std::is_same<gc, typename ordered_list::gc>::value, "GC and OrderedList::gc must be the same");
161
162         static_assert(!std::is_same<item_counter, atomicity::empty_item_counter>::value,
163             "atomicity::empty_item_counter is not allowed as a item counter");
164
165         //@cond
166         typedef typename ordered_list::template select_stat_wrapper< typename ordered_list::stat > bucket_stat;
167
168         typedef typename ordered_list::template rebind_traits<
169             cds::opt::item_counter< cds::atomicity::empty_item_counter >
170             , cds::opt::stat< typename bucket_stat::wrapped_stat >
171         >::type internal_bucket_type_;
172
173         class internal_bucket_type: public internal_bucket_type_
174         {
175             typedef internal_bucket_type_ base_class;
176         public:
177             using base_class::base_class;
178             using typename base_class::node_type;
179             using base_class::alloc_node;
180             using base_class::insert_node;
181             using base_class::node_to_value;
182         };
183
184         typedef typename internal_bucket_type::exempt_ptr exempt_ptr;
185         typedef typename internal_bucket_type::raw_ptr    raw_ptr;
186         typedef typename bucket_stat::stat stat;
187         //@endcond
188
189     protected:
190         //@cond
191         /// Bucket table allocator
192         typedef typename allocator::template rebind< internal_bucket_type >::other bucket_table_allocator;
193
194         const size_t            m_nHashBitmask;
195         item_counter            m_ItemCounter; ///< Item counter
196         hash                    m_HashFunctor; ///< Hash functor
197         internal_bucket_type*   m_Buckets;     ///< bucket table
198         stat                    m_Stat;        ///< Internal statistics
199         //@endcond
200
201     public:
202     ///@name Forward iterators (thread-safe under RCU lock)
203     //@{
204         /// Forward iterator
205         /**
206             The forward iterator for Michael's set is based on \p OrderedList forward iterator and has some features:
207             - it has no post-increment operator
208             - it iterates items in unordered fashion
209
210             You may safely use iterators in multi-threaded environment only under RCU lock.
211             Otherwise, a crash is possible if another thread deletes the element the iterator points to.
212
213             The iterator interface:
214             \code
215             class iterator {
216             public:
217                 // Default constructor
218                 iterator();
219
220                 // Copy construtor
221                 iterator( iterator const& src );
222
223                 // Dereference operator
224                 value_type * operator ->() const;
225
226                 // Dereference operator
227                 value_type& operator *() const;
228
229                 // Preincrement operator
230                 iterator& operator ++();
231
232                 // Assignment operator
233                 iterator& operator = (iterator const& src);
234
235                 // Equality operators
236                 bool operator ==(iterator const& i ) const;
237                 bool operator !=(iterator const& i ) const;
238             };
239             \endcode
240         */
241         typedef michael_set::details::iterator< internal_bucket_type, false >    iterator;
242
243         /// Const forward iterator
244         typedef michael_set::details::iterator< internal_bucket_type, true >     const_iterator;
245
246         /// Returns a forward iterator addressing the first element in a set
247         /**
248             For empty set \code begin() == end() \endcode
249         */
250         iterator begin()
251         {
252             return iterator( m_Buckets[0].begin(), m_Buckets, m_Buckets + bucket_count());
253         }
254
255         /// Returns an iterator that addresses the location succeeding the last element in a set
256         /**
257             Do not use the value returned by <tt>end</tt> function to access any item.
258             The returned value can be used only to control reaching the end of the set.
259             For empty set \code begin() == end() \endcode
260         */
261         iterator end()
262         {
263             return iterator( m_Buckets[bucket_count() - 1].end(), m_Buckets + bucket_count() - 1, m_Buckets + bucket_count());
264         }
265
266         /// Returns a forward const iterator addressing the first element in a set
267         const_iterator begin() const
268         {
269             return get_const_begin();
270         }
271
272         /// Returns a forward const iterator addressing the first element in a set
273         const_iterator cbegin() const
274         {
275             return get_const_begin();
276         }
277
278         /// Returns an const iterator that addresses the location succeeding the last element in a set
279         const_iterator end() const
280         {
281             return get_const_end();
282         }
283
284         /// Returns an const iterator that addresses the location succeeding the last element in a set
285         const_iterator cend() const
286         {
287             return get_const_end();
288         }
289     //@}
290
291     public:
292         /// Initialize hash set
293         /**
294             The Michael's hash set is non-expandable container. You should point the average count of items \p nMaxItemCount
295             when you create an object.
296             \p nLoadFactor parameter defines average count of items per bucket and it should be small number between 1 and 10.
297             Remember, since the bucket implementation is an ordered list, searching in the bucket is linear [<tt>O(nLoadFactor)</tt>].
298
299             The ctor defines hash table size as rounding <tt>nMaxItemCount / nLoadFactor</tt> up to nearest power of two.
300         */
301         MichaelHashSet(
302             size_t nMaxItemCount,   ///< estimation of max item count in the hash set
303             size_t nLoadFactor      ///< load factor: estimation of max number of items in the bucket
304         ) : m_nHashBitmask( michael_set::details::init_hash_bitmask( nMaxItemCount, nLoadFactor ))
305           , m_Buckets( bucket_table_allocator().allocate( bucket_count()))
306         {
307             for ( auto it = m_Buckets, itEnd = m_Buckets + bucket_count(); it != itEnd; ++it )
308                 construct_bucket<bucket_stat>( it );
309         }
310
311         /// Clears hash set and destroys it
312         ~MichaelHashSet()
313         {
314             clear();
315
316             for ( auto it = m_Buckets, itEnd = m_Buckets + bucket_count(); it != itEnd; ++it )
317                 it->~internal_bucket_type();
318             bucket_table_allocator().deallocate( m_Buckets, bucket_count());
319
320         }
321
322         /// Inserts new node
323         /**
324             The function creates a node with copy of \p val value
325             and then inserts the node created into the set.
326
327             The type \p Q should contain as minimum the complete key for the node.
328             The object of \ref value_type should be constructible from a value of type \p Q.
329             In trivial case, \p Q is equal to \ref value_type.
330
331             The function applies RCU lock internally.
332
333             Returns \p true if \p val is inserted into the set, \p false otherwise.
334         */
335         template <typename Q>
336         bool insert( Q&& val )
337         {
338             const bool bRet = bucket( val ).insert( std::forward<Q>( val ));
339             if ( bRet )
340                 ++m_ItemCounter;
341             return bRet;
342         }
343
344         /// Inserts new node
345         /**
346             The function allows to split creating of new item into two part:
347             - create item with key only
348             - insert new item into the set
349             - if inserting is success, calls  \p f functor to initialize value-fields of \p val.
350
351             The functor signature is:
352             \code
353                 void func( value_type& val );
354             \endcode
355             where \p val is the item inserted.
356             The user-defined functor is called only if the inserting is success.
357
358             The function applies RCU lock internally.
359
360             @warning For \ref cds_nonintrusive_MichaelList_rcu "MichaelList" as the bucket see \ref cds_intrusive_item_creating "insert item troubleshooting".
361             \ref cds_nonintrusive_LazyList_rcu "LazyList" provides exclusive access to inserted item and does not require any node-level
362             synchronization.
363             */
364         template <typename Q, typename Func>
365         bool insert( Q&& val, Func f )
366         {
367             const bool bRet = bucket( val ).insert( std::forward<Q>( val ), f );
368             if ( bRet )
369                 ++m_ItemCounter;
370             return bRet;
371         }
372
373         /// Updates the element
374         /**
375             The operation performs inserting or changing data with lock-free manner.
376
377             If the item \p val not found in the set, then \p val is inserted iff \p bAllowInsert is \p true.
378             Otherwise, the functor \p func is called with item found.
379             The functor signature is:
380             \code
381                 struct functor {
382                     void operator()( bool bNew, value_type& item, Q const& val );
383                 };
384             \endcode
385             with arguments:
386             - \p bNew - \p true if the item has been inserted, \p false otherwise
387             - \p item - item of the set
388             - \p val - argument \p val passed into the \p %update() function
389
390             The functor may change non-key fields of the \p item.
391
392             The function applies RCU lock internally.
393
394             Returns <tt> std::pair<bool, bool> </tt> where \p first is \p true if operation is successful,
395             \p second is \p true if new item has been added or \p false if the item with \p key
396             already is in the set.
397
398             @warning For \ref cds_intrusive_MichaelList_hp "MichaelList" as the bucket see \ref cds_intrusive_item_creating "insert item troubleshooting".
399             \ref cds_intrusive_LazyList_hp "LazyList" provides exclusive access to inserted item and does not require any node-level
400             synchronization.
401         */
402         template <typename Q, typename Func>
403         std::pair<bool, bool> update( Q const& val, Func func, bool bAllowInsert = true )
404         {
405             std::pair<bool, bool> bRet = bucket( val ).update( val, func, bAllowInsert );
406             if ( bRet.second )
407                 ++m_ItemCounter;
408             return bRet;
409         }//@cond
410         template <typename Q, typename Func>
411         CDS_DEPRECATED("ensure() is deprecated, use update()")
412         std::pair<bool, bool> ensure( const Q& val, Func func )
413         {
414             return update( val, func, true );
415         }
416         //@endcond
417
418         /// Inserts data of type \p value_type created from \p args
419         /**
420             Returns \p true if inserting successful, \p false otherwise.
421
422             The function applies RCU lock internally.
423         */
424         template <typename... Args>
425         bool emplace( Args&&... args )
426         {
427             typename internal_bucket_type::node_type * pNode = internal_bucket_type::alloc_node( std::forward<Args>( args )... );
428             bool bRet = bucket( internal_bucket_type::node_to_value( *pNode )).insert_node( pNode );
429             if ( bRet )
430                 ++m_ItemCounter;
431             return bRet;
432         }
433
434         /// Deletes \p key from the set
435         /** \anchor cds_nonintrusive_MichealSet_rcu_erase_val
436
437             Since the key of MichaelHashSet's item type \p value_type is not explicitly specified,
438             template parameter \p Q defines the key type searching in the list.
439             The set item comparator should be able to compare the type \p value_type
440             and the type \p Q.
441
442             RCU \p synchronize method can be called. RCU should not be locked.
443
444             Return \p true if key is found and deleted, \p false otherwise
445         */
446         template <typename Q>
447         bool erase( Q const& key )
448         {
449             const bool bRet = bucket( key ).erase( key );
450             if ( bRet )
451                 --m_ItemCounter;
452             return bRet;
453         }
454
455         /// Deletes the item from the set using \p pred predicate for searching
456         /**
457             The function is an analog of \ref cds_nonintrusive_MichealSet_rcu_erase_val "erase(Q const&)"
458             but \p pred is used for key comparing.
459             \p Less functor has the interface like \p std::less.
460             \p Less must imply the same element order as the comparator used for building the set.
461         */
462         template <typename Q, typename Less>
463         bool erase_with( Q const& key, Less pred )
464         {
465             const bool bRet = bucket( key ).erase_with( key, pred );
466             if ( bRet )
467                 --m_ItemCounter;
468             return bRet;
469         }
470
471         /// Deletes \p key from the set
472         /** \anchor cds_nonintrusive_MichealSet_rcu_erase_func
473
474             The function searches an item with key \p key, calls \p f functor
475             and deletes the item. If \p key is not found, the functor is not called.
476
477             The functor \p Func interface:
478             \code
479             struct extractor {
480                 void operator()(value_type const& val);
481             };
482             \endcode
483
484             Since the key of %MichaelHashSet's \p value_type is not explicitly specified,
485             template parameter \p Q defines the key type searching in the list.
486             The list item comparator should be able to compare the type \p T of list item
487             and the type \p Q.
488
489             RCU \p synchronize method can be called. RCU should not be locked.
490
491             Return \p true if key is found and deleted, \p false otherwise
492         */
493         template <typename Q, typename Func>
494         bool erase( Q const& key, Func f )
495         {
496             const bool bRet = bucket( key ).erase( key, f );
497             if ( bRet )
498                 --m_ItemCounter;
499             return bRet;
500         }
501
502         /// Deletes the item from the set using \p pred predicate for searching
503         /**
504             The function is an analog of \ref cds_nonintrusive_MichealSet_rcu_erase_func "erase(Q const&, Func)"
505             but \p pred is used for key comparing.
506             \p Less functor has the interface like \p std::less.
507             \p Less must imply the same element order as the comparator used for building the set.
508         */
509         template <typename Q, typename Less, typename Func>
510         bool erase_with( Q const& key, Less pred, Func f )
511         {
512             const bool bRet = bucket( key ).erase_with( key, pred, f );
513             if ( bRet )
514                 --m_ItemCounter;
515             return bRet;
516         }
517
518         /// Extracts an item from the set
519         /** \anchor cds_nonintrusive_MichaelHashSet_rcu_extract
520             The function searches an item with key equal to \p key in the set,
521             unlinks it from the set, and returns \ref cds::urcu::exempt_ptr "exempt_ptr" pointer to the item found.
522             If the item with the key equal to \p key is not found the function return an empty \p exempt_ptr.
523
524             The function just excludes the item from the set and returns a pointer to item found.
525             Depends on \p ordered_list you should or should not lock RCU before calling of this function:
526             - for the set based on \ref cds_nonintrusive_MichaelList_rcu "MichaelList" RCU should not be locked
527             - for the set based on \ref cds_nonintrusive_LazyList_rcu "LazyList" RCU should be locked
528             See ordered list implementation for details.
529
530             \code
531             #include <cds/urcu/general_buffered.h>
532             #include <cds/container/michael_list_rcu.h>
533             #include <cds/container/michael_set_rcu.h>
534
535             typedef cds::urcu::gc< general_buffered<> > rcu;
536             typedef cds::container::MichaelList< rcu, Foo > rcu_michael_list;
537             typedef cds::container::MichaelHashSet< rcu, rcu_michael_list, foo_traits > rcu_michael_set;
538
539             rcu_michael_set theSet;
540             // ...
541
542             typename rcu_michael_set::exempt_ptr p;
543
544             // For MichaelList we should not lock RCU
545
546             // Note that you must not delete the item found inside the RCU lock
547             p = theSet.extract( 10 );
548             if ( p ) {
549                 // do something with p
550                 ...
551             }
552
553             // We may safely release p here
554             // release() passes the pointer to RCU reclamation cycle
555             p.release();
556             \endcode
557         */
558         template <typename Q>
559         exempt_ptr extract( Q const& key )
560         {
561             exempt_ptr p = bucket( key ).extract( key );
562             if ( p )
563                 --m_ItemCounter;
564             return p;
565         }
566
567         /// Extracts an item from the set using \p pred predicate for searching
568         /**
569             The function is an analog of \p extract(Q const&) but \p pred is used for key comparing.
570             \p Less functor has the interface like \p std::less.
571             \p pred must imply the same element order as the comparator used for building the set.
572         */
573         template <typename Q, typename Less>
574         exempt_ptr extract_with( Q const& key, Less pred )
575         {
576             exempt_ptr p = bucket( key ).extract_with( key, pred );
577             if ( p )
578                 --m_ItemCounter;
579             return p;
580         }
581
582         /// Finds the key \p key
583         /** \anchor cds_nonintrusive_MichealSet_rcu_find_func
584
585             The function searches the item with key equal to \p key and calls the functor \p f for item found.
586             The interface of \p Func functor is:
587             \code
588             struct functor {
589                 void operator()( value_type& item, Q& key );
590             };
591             \endcode
592             where \p item is the item found, \p key is the <tt>find</tt> function argument.
593
594             The functor may change non-key fields of \p item. Note that the functor is only guarantee
595             that \p item cannot be disposed during functor is executing.
596             The functor does not serialize simultaneous access to the set's \p item. If such access is
597             possible you must provide your own synchronization schema on item level to exclude unsafe item modifications.
598
599             The \p key argument is non-const since it can be used as \p f functor destination i.e., the functor
600             can modify both arguments.
601
602             Note the hash functor specified for class \p Traits template parameter
603             should accept a parameter of type \p Q that may be not the same as \p value_type.
604
605             The function applies RCU lock internally.
606
607             The function returns \p true if \p key is found, \p false otherwise.
608         */
609         template <typename Q, typename Func>
610         bool find( Q& key, Func f )
611         {
612             return bucket( key ).find( key, f );
613         }
614         //@cond
615         template <typename Q, typename Func>
616         bool find( Q const& key, Func f )
617         {
618             return bucket( key ).find( key, f );
619         }
620         //@endcond
621
622         /// Finds the key \p key using \p pred predicate for searching
623         /**
624             The function is an analog of \ref cds_nonintrusive_MichealSet_rcu_find_func "find(Q&, Func)"
625             but \p pred is used for key comparing.
626             \p Less functor has the interface like \p std::less.
627             \p Less must imply the same element order as the comparator used for building the set.
628         */
629         template <typename Q, typename Less, typename Func>
630         bool find_with( Q& key, Less pred, Func f )
631         {
632             return bucket( key ).find_with( key, pred, f );
633         }
634         //@cond
635         template <typename Q, typename Less, typename Func>
636         bool find_with( Q const& key, Less pred, Func f )
637         {
638             return bucket( key ).find_with( key, pred, f );
639         }
640         //@endcond
641
642         /// Checks whether the set contains \p key
643         /**
644
645             The function searches the item with key equal to \p key
646             and returns \p true if the key is found, and \p false otherwise.
647
648             Note the hash functor specified for class \p Traits template parameter
649             should accept a parameter of type \p Q that can be not the same as \p value_type.
650         */
651         template <typename Q>
652         bool contains( Q const& key )
653         {
654             return bucket( key ).contains( key );
655         }
656         //@cond
657         template <typename Q>
658         CDS_DEPRECATED("use contains()")
659         bool find( Q const& key )
660         {
661             return contains( key );
662         }
663         //@endcond
664
665         /// Checks whether the set contains \p key using \p pred predicate for searching
666         /**
667             The function is an analog of <tt>contains( key )</tt> but \p pred is used for key comparing.
668             \p Less functor has the interface like \p std::less.
669             \p Less must imply the same element order as the comparator used for building the set.
670         */
671         template <typename Q, typename Less>
672         bool contains( Q const& key, Less pred )
673         {
674             return bucket( key ).contains( key, pred );
675         }
676         //@cond
677         template <typename Q, typename Less>
678         CDS_DEPRECATED("use contains()")
679         bool find_with( Q const& key, Less pred )
680         {
681             return contains( key, pred );
682         }
683         //@endcond
684
685         /// Finds the key \p key and return the item found
686         /** \anchor cds_nonintrusive_MichaelHashSet_rcu_get
687             The function searches the item with key equal to \p key and returns the pointer to item found.
688             If \p key is not found it returns \p nullptr.
689             Note the type of returned value depends on underlying \p ordered_list.
690             For details, see documentation of ordered list you use.
691
692             Note the compare functor should accept a parameter of type \p Q that can be not the same as \p value_type.
693
694             RCU should be locked before call of this function.
695             Returned item is valid only while RCU is locked:
696             \code
697             typedef cds::container::MichaelHashSet< your_template_parameters > hash_set;
698             hash_set theSet;
699             typename hash_set::raw_ptr gp;
700             // ...
701             {
702                 // Lock RCU
703                 hash_set::rcu_lock lock;
704
705                 gp = theSet.get( 5 );
706                 if ( gp ) {
707                     // Deal with pVal
708                     //...
709                 }
710                 // Unlock RCU by rcu_lock destructor
711                 // gp can be reclaimed at any time after RCU has been unlocked
712             }
713             \endcode
714         */
715         template <typename Q>
716         raw_ptr get( Q const& key )
717         {
718             return bucket( key ).get( key );
719         }
720
721         /// Finds the key \p key and return the item found
722         /**
723             The function is an analog of \ref cds_nonintrusive_MichaelHashSet_rcu_get "get(Q const&)"
724             but \p pred is used for comparing the keys.
725
726             \p Less functor has the semantics like \p std::less but should take arguments of type \ref value_type and \p Q
727             in any order.
728             \p pred must imply the same element order as the comparator used for building the set.
729         */
730         template <typename Q, typename Less>
731         raw_ptr get_with( Q const& key, Less pred )
732         {
733             return bucket( key ).get_with( key, pred );
734         }
735
736         /// Clears the set (not atomic)
737         void clear()
738         {
739             for ( size_t i = 0; i < bucket_count(); ++i )
740                 m_Buckets[i].clear();
741             m_ItemCounter.reset();
742         }
743
744         /// Checks if the set is empty
745         /**
746             Emptiness is checked by item counting: if item count is zero then the set is empty.
747             Thus, the correct item counting feature is an important part of Michael's set implementation.
748         */
749         bool empty() const
750         {
751             return size() == 0;
752         }
753
754         /// Returns item count in the set
755         size_t size() const
756         {
757             return m_ItemCounter;
758         }
759
760         /// Returns const reference to internal statistics
761         stat const& statistics() const
762         {
763             return m_Stat;
764         }
765
766         /// Returns the size of hash table
767         /**
768             Since \p %MichaelHashSet cannot dynamically extend the hash table size,
769             the value returned is an constant depending on object initialization parameters;
770             see MichaelHashSet::MichaelHashSet for explanation.
771         */
772         size_t bucket_count() const
773         {
774             return m_nHashBitmask + 1;
775         }
776
777     protected:
778         //@cond
779         /// Calculates hash value of \p key
780         template <typename Q>
781         size_t hash_value( Q const& key ) const
782         {
783             return m_HashFunctor( key ) & m_nHashBitmask;
784         }
785
786         /// Returns the bucket (ordered list) for \p key
787         template <typename Q>
788         internal_bucket_type& bucket( Q const& key )
789         {
790             return m_Buckets[hash_value( key )];
791         }
792         template <typename Q>
793         internal_bucket_type const& bucket( Q const& key ) const
794         {
795             return m_Buckets[hash_value( key )];
796         }
797
798         template <typename Stat>
799         typename std::enable_if< Stat::empty >::type construct_bucket( internal_bucket_type* bucket )
800         {
801             new (bucket) internal_bucket_type;
802         }
803
804         template <typename Stat>
805         typename std::enable_if< !Stat::empty >::type construct_bucket( internal_bucket_type* bucket )
806         {
807             new (bucket) internal_bucket_type( m_Stat );
808         }
809
810         const_iterator get_const_begin() const
811         {
812             return const_iterator( const_cast<internal_bucket_type const&>(m_Buckets[0]).begin(), m_Buckets, m_Buckets + bucket_count());
813         }
814         const_iterator get_const_end() const
815         {
816             return const_iterator( const_cast<internal_bucket_type const&>(m_Buckets[bucket_count() - 1]).end(), m_Buckets + bucket_count() - 1, m_Buckets + bucket_count());
817         }
818         //@endcond
819     };
820
821 }} // namespace cds::container
822
823 #endif // ifndef CDSLIB_CONTAINER_MICHAEL_SET_RCU_H