EllenBinTreeMap refactoring
[libcds.git] / cds / container / impl / ellen_bintree_set.h
1 //$$CDS-header$$
2
3 #ifndef __CDS_CONTAINER_IMPL_ELLEN_BINTREE_SET_H
4 #define __CDS_CONTAINER_IMPL_ELLEN_BINTREE_SET_H
5
6 #include <traits>
7 #include <cds/container/details/ellen_bintree_base.h>
8 #include <cds/intrusive/impl/ellen_bintree.h>
9 #include <cds/container/details/guarded_ptr_cast.h>
10
11 namespace cds { namespace container {
12
13     /// Set based on Ellen's et al binary search tree
14     /** @ingroup cds_nonintrusive_set
15         @ingroup cds_nonintrusive_tree
16         @anchor cds_container_EllenBinTreeSet
17
18         Source:
19             - [2010] F.Ellen, P.Fatourou, E.Ruppert, F.van Breugel "Non-blocking Binary Search Tree"
20
21         %EllenBinTreeSet is an unbalanced leaf-oriented binary search tree that implements the <i>set</i>
22         abstract data type. Nodes maintains child pointers but not parent pointers.
23         Every internal node has exactly two children, and all data of type \p T currently in
24         the tree are stored in the leaves. Internal nodes of the tree are used to direct \p find
25         operation along the path to the correct leaf. The keys (of \p Key type) stored in internal nodes
26         may or may not be in the set. \p Key type is a subset of \p T type.
27         There should be exactly defined a key extracting functor for converting object of type \p T to
28         object of type \p Key.
29
30         Due to \p extract_min and \p extract_max member functions the \p %EllenBinTreeSet can act as
31         a <i>priority queue</i>. In this case you should provide unique compound key, for example,
32         the priority value plus some uniformly distributed random value.
33
34         @warning Recall the tree is <b>unbalanced</b>. The complexity of operations is <tt>O(log N)</tt>
35         for uniformly distributed random keys, but in worst case the complexity is <tt>O(N)</tt>.
36
37         @note In the current implementation we do not use helping technique described in the original paper.
38         In Hazard Pointer schema helping is too complicated and does not give any observable benefits.
39         Instead of helping, when a thread encounters a concurrent operation it just spins waiting for
40         the operation done. Such solution allows greatly simplify the implementation of tree.
41
42         <b>Template arguments</b> :
43         - \p GC - safe memory reclamation (i.e. light-weight garbage collector) type, like \p cds::gc::HP, cds::gc::DHP
44         - \p Key - key type, a subset of \p T
45         - \p T - type to be stored in tree's leaf nodes.
46         - \p Traits - set traits, default is \p ellen_bintree::traits
47             It is possible to declare option-based tree with \p ellen_bintree::make_set_traits metafunction
48             instead of \p Traits template argument.
49
50         @note Do not include <tt><cds/container/impl/ellen_bintree_set.h></tt> header file directly.
51         There are header file for each GC type:
52         - <tt><cds/container/ellen_bintree_set_hp.h></tt> - for \p cds::gc::HP
53         - <tt><cds/container/ellen_bintree_set_dhp.h></tt> - for \p cds::gc::DHP
54         - <tt><cds/container/ellen_bintree_set_rcu.h></tt> - for RCU GC
55             (see \ref cds_container_EllenBinTreeSet_rcu "RCU-based EllenBinTreeSet")
56
57         @anchor cds_container_EllenBinTreeSet_less
58         <b>Predicate requirements</b>
59
60         \p Traits::less, \p Traits::compare and other predicates using with member fuctions should accept at least parameters
61         of type \p T and \p Key in any combination.
62         For example, for \p Foo struct with \p std::string key field the appropiate \p less functor is:
63         \code
64         struct Foo
65         {
66             std::string m_strKey;
67             ...
68         };
69
70         struct less {
71             bool operator()( Foo const& v1, Foo const& v2 ) const
72             { return v1.m_strKey < v2.m_strKey ; }
73
74             bool operator()( Foo const& v, std::string const& s ) const
75             { return v.m_strKey < s ; }
76
77             bool operator()( std::string const& s, Foo const& v ) const
78             { return s < v.m_strKey ; }
79
80             // Support comparing std::string and char const *
81             bool operator()( std::string const& s, char const * p ) const
82             { return s.compare(p) < 0 ; }
83
84             bool operator()( Foo const& v, char const * p ) const
85             { return v.m_strKey.compare(p) < 0 ; }
86
87             bool operator()( char const * p, std::string const& s ) const
88             { return s.compare(p) > 0; }
89
90             bool operator()( char const * p, Foo const& v ) const
91             { return v.m_strKey.compare(p) > 0; }
92         };
93         \endcode
94     */
95     template <
96         class GC,
97         typename Key,
98         typename T,
99 #ifdef CDS_DOXYGEN_INVOKED
100         class Traits = ellen_bintree::traits
101 #else
102         class Traits
103 #endif
104     >
105     class EllenBinTreeSet
106 #ifdef CDS_DOXYGEN_INVOKED
107         : public cds::intrusive::EllenBinTree< GC, Key, T, Traits >
108 #else
109         : public ellen_bintree::details::make_ellen_bintree_set< GC, Key, T, Traits >::type
110 #endif
111     {
112         //@cond
113         typedef ellen_bintree::details::make_ellen_bintree_set< GC, Key, T, Traits > maker;
114         typedef typename maker::type base_class;
115         //@endcond
116
117     public:
118         typedef GC      gc;         ///< Garbage collector
119         typedef Key     key_type;   ///< type of a key to be stored in internal nodes; key is a part of \p value_type
120         typedef T       value_type; ///< type of value to be stored in the binary tree
121         typedef Traits  traits;    ///< Traits template parameter
122
123 #   ifdef CDS_DOXYGEN_INVOKED
124         typedef implementation_defined key_comparator  ;    ///< key compare functor based on opt::compare and opt::less option setter.
125 #   else
126         typedef typename maker::intrusive_type_traits::compare   key_comparator;
127 #   endif
128         typedef typename base_class::item_counter           item_counter;  ///< Item counting policy used
129         typedef typename base_class::memory_model           memory_model;  ///< Memory ordering. See cds::opt::memory_model option
130         typedef typename base_class::stat                   stat;          ///< internal statistics type
131         typedef typename traits::key_extractor              key_extractor; ///< key extracting functor
132
133         typedef typename traits::allocator                  allocator_type;   ///< Allocator for leaf nodes
134         typedef typename base_class::node_allocator         node_allocator;   ///< Internal node allocator
135         typedef typename base_class::update_desc_allocator  update_desc_allocator; ///< Update descriptor allocator
136
137     protected:
138         //@cond
139         typedef typename maker::cxx_leaf_node_allocator cxx_leaf_node_allocator;
140         typedef typename base_class::value_type         leaf_node;
141         typedef typename base_class::internal_node      internal_node;
142
143         typedef std::unique_ptr< leaf_node, typename maker::leaf_deallocator > scoped_node_ptr;
144         //@endcond
145
146     public:
147         /// Guarded pointer
148         typedef cds::gc::guarded_ptr< gc, leaf_node, value_type, details::guarded_ptr_cast_set<leaf_node, value_type> > guarded_ptr;
149
150     public:
151         /// Default constructor
152         EllenBinTreeSet()
153             : base_class()
154         {}
155
156         /// Clears the set
157         ~EllenBinTreeSet()
158         {}
159
160         /// Inserts new node
161         /**
162             The function creates a node with copy of \p val value
163             and then inserts the node created into the set.
164
165             The type \p Q should contain at least the complete key for the node.
166             The object of \ref value_type should be constructible from a value of type \p Q.
167             In trivial case, \p Q is equal to \ref value_type.
168
169             Returns \p true if \p val is inserted into the set, \p false otherwise.
170         */
171         template <typename Q>
172         bool insert( Q const& val )
173         {
174             scoped_node_ptr sp( cxx_leaf_node_allocator().New( val ));
175             if ( base_class::insert( *sp.get() )) {
176                 sp.release();
177                 return true;
178             }
179             return false;
180         }
181
182         /// Inserts new node
183         /**
184             The function allows to split creating of new item into two part:
185             - create item with key only
186             - insert new item into the set
187             - if inserting is success, calls  \p f functor to initialize value-fields of \p val.
188
189             The functor signature is:
190             \code
191                 void func( value_type& val );
192             \endcode
193             where \p val is the item inserted. User-defined functor \p f should guarantee that during changing
194             \p val no any other changes could be made on this set's item by concurrent threads.
195             The user-defined functor is called only if the inserting is success.
196         */
197         template <typename Q, typename Func>
198         bool insert( Q const& val, Func f )
199         {
200             scoped_node_ptr sp( cxx_leaf_node_allocator().New( val ));
201             if ( base_class::insert( *sp.get(), [&f]( leaf_node& val ) { f( val.m_Value ); } )) {
202                 sp.release();
203                 return true;
204             }
205             return false;
206         }
207
208         /// Ensures that the item exists in the set
209         /**
210             The operation performs inserting or changing data with lock-free manner.
211
212             If the \p val key not found in the set, then the new item created from \p val
213             is inserted into the set. Otherwise, the functor \p func is called with the item found.
214             The functor \p Func should be a function with signature:
215             \code
216                 void func( bool bNew, value_type& item, const Q& val );
217             \endcode
218             or a functor:
219             \code
220                 struct my_functor {
221                     void operator()( bool bNew, value_type& item, const Q& val );
222                 };
223             \endcode
224
225             with arguments:
226             - \p bNew - \p true if the item has been inserted, \p false otherwise
227             - \p item - item of the set
228             - \p val - argument \p key passed into the \p ensure function
229
230             The functor may change non-key fields of the \p item; however, \p func must guarantee
231             that during changing no any other modifications could be made on this item by concurrent threads.
232
233             Returns <tt> std::pair<bool, bool> </tt> where \p first is true if operation is successfull,
234             \p second is true if new item has been added or \p false if the item with \p key
235             already is in the set.
236
237             @warning See \ref cds_intrusive_item_creating "insert item troubleshooting"
238         */
239         template <typename Q, typename Func>
240         std::pair<bool, bool> ensure( const Q& val, Func func )
241         {
242             scoped_node_ptr sp( cxx_leaf_node_allocator().New( val ));
243             std::pair<bool, bool> bRes = base_class::ensure( *sp,
244                 [&func, &val](bool bNew, leaf_node& node, leaf_node&){ func( bNew, node.m_Value, val ); });
245             if ( bRes.first && bRes.second )
246                 sp.release();
247             return bRes;
248         }
249
250         /// Inserts data of type \p value_type created in-place from \p args
251         /**
252             Returns \p true if inserting successful, \p false otherwise.
253         */
254         template <typename... Args>
255         bool emplace( Args&&... args )
256         {
257             scoped_node_ptr sp( cxx_leaf_node_allocator().New( std::forward<Args>(args)... ));
258             if ( base_class::insert( *sp.get() )) {
259                 sp.release();
260                 return true;
261             }
262             return false;
263         }
264
265         /// Delete \p key from the set
266         /** \anchor cds_nonintrusive_EllenBinTreeSet_erase_val
267
268             The item comparator should be able to compare the type \p value_type
269             and the type \p Q.
270
271             Return \p true if key is found and deleted, \p false otherwise
272         */
273         template <typename Q>
274         bool erase( Q const& key )
275         {
276             return base_class::erase( key );
277         }
278
279         /// Deletes the item from the set using \p pred predicate for searching
280         /**
281             The function is an analog of \ref cds_nonintrusive_EllenBinTreeSet_erase_val "erase(Q const&)"
282             but \p pred is used for key comparing.
283             \p Less functor has the interface like \p std::less.
284             \p Less must imply the same element order as the comparator used for building the set.
285         */
286         template <typename Q, typename Less>
287         bool erase_with( Q const& key, Less pred )
288         {
289             return base_class::erase_with( key, cds::details::predicate_wrapper< leaf_node, Less, typename maker::value_accessor >());
290         }
291
292         /// Delete \p key from the set
293         /** \anchor cds_nonintrusive_EllenBinTreeSet_erase_func
294
295             The function searches an item with key \p key, calls \p f functor
296             and deletes the item. If \p key is not found, the functor is not called.
297
298             The functor \p Func interface:
299             \code
300             struct extractor {
301                 void operator()(value_type const& val);
302             };
303             \endcode
304
305             Since the key of MichaelHashSet's \p value_type is not explicitly specified,
306             template parameter \p Q defines the key type searching in the list.
307             The list item comparator should be able to compare the type \p T of list item
308             and the type \p Q.
309
310             Return \p true if key is found and deleted, \p false otherwise
311         */
312         template <typename Q, typename Func>
313         bool erase( Q const& key, Func f )
314         {
315             return base_class::erase( key, [&f]( leaf_node const& node) { f( node.m_Value ); } );
316         }
317
318         /// Deletes the item from the set using \p pred predicate for searching
319         /**
320             The function is an analog of \ref cds_nonintrusive_EllenBinTreeSet_erase_func "erase(Q const&, Func)"
321             but \p pred is used for key comparing.
322             \p Less functor has the interface like \p std::less.
323             \p Less must imply the same element order as the comparator used for building the set.
324         */
325         template <typename Q, typename Less, typename Func>
326         bool erase_with( Q const& key, Less pred, Func f )
327         {
328             return base_class::erase_with( key, cds::details::predicate_wrapper< leaf_node, Less, typename maker::value_accessor >(),
329                 [&f]( leaf_node const& node) { f( node.m_Value ); } );
330         }
331
332         /// Extracts an item with minimal key from the set
333         /**
334             If the set is not empty, the function returns \p true, \p result contains a pointer to minimum value.
335             If the set is empty, the function returns \p false, \p result is left unchanged.
336
337             @note Due the concurrent nature of the set, the function extracts <i>nearly</i> minimum key.
338             It means that the function gets leftmost leaf of the tree and tries to unlink it.
339             During unlinking, a concurrent thread may insert an item with key less than leftmost item's key.
340             So, the function returns the item with minimum key at the moment of tree traversing.
341
342             The guarded pointer \p dest prevents deallocation of returned item,
343             see cds::gc::guarded_ptr for explanation.
344             @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
345         */
346         bool extract_min( guarded_ptr& result )
347         {
348             return base_class::extract_min_( result.guard() );
349         }
350
351         /// Extracts an item with maximal key from the set
352         /**
353             If the set is not empty, the function returns \p true, \p result contains a pointer to maximal value.
354             If the set is empty, the function returns \p false, \p result is left unchanged.
355
356             @note Due the concurrent nature of the set, the function extracts <i>nearly</i> maximal key.
357             It means that the function gets rightmost leaf of the tree and tries to unlink it.
358             During unlinking, a concurrent thread may insert an item with key great than leftmost item's key.
359             So, the function returns the item with maximum key at the moment of tree traversing.
360
361             The guarded pointer \p dest prevents deallocation of returned item,
362             see cds::gc::guarded_ptr for explanation.
363             @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
364         */
365         bool extract_max( guarded_ptr& result )
366         {
367             return base_class::extract_max_( result.guard() );
368         }
369
370         /// Extracts an item from the tree
371         /** \anchor cds_nonintrusive_EllenBinTreeSet_extract
372             The function searches an item with key equal to \p key in the tree,
373             unlinks it, and returns pointer to an item found in \p result parameter.
374             If the item  is not found the function returns \p false.
375
376             The guarded pointer \p dest prevents deallocation of returned item,
377             see cds::gc::guarded_ptr for explanation.
378             @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
379         */
380         template <typename Q>
381         bool extract( guarded_ptr& result, Q const& key )
382         {
383             return base_class::extract_( result.guard(), key );
384         }
385
386         /// Extracts an item from the set using \p pred for searching
387         /**
388             The function is an analog of \ref cds_nonintrusive_EllenBinTreeSet_extract "extract(guarded_ptr& dest, Q const&)"
389             but \p pred is used for key compare.
390             \p Less has the interface like \p std::less.
391             \p pred must imply the same element order as the comparator used for building the set.
392         */
393         template <typename Q, typename Less>
394         bool extract_with( guarded_ptr& result, Q const& key, Less pred )
395         {
396             return base_class::extract_with_( result.guard(), key,
397                 cds::details::predicate_wrapper< leaf_node, Less, typename maker::value_accessor >());
398         }
399
400         /// Find the key \p key
401         /**
402             @anchor cds_nonintrusive_EllenBinTreeSet_find_func
403
404             The function searches the item with key equal to \p key and calls the functor \p f for item found.
405             The interface of \p Func functor is:
406             \code
407             struct functor {
408                 void operator()( value_type& item, Q& key );
409             };
410             \endcode
411             where \p item is the item found, \p key is the <tt>find</tt> function argument.
412
413             You may pass \p f argument by reference using \p std::ref.
414
415             The functor may change non-key fields of \p item. Note that the functor is only guarantee
416             that \p item cannot be disposed during functor is executing.
417             The functor does not serialize simultaneous access to the set's \p item. If such access is
418             possible you must provide your own synchronization schema on item level to exclude unsafe item modifications.
419
420             The \p key argument is non-const since it can be used as \p f functor destination i.e., the functor
421             can modify both arguments.
422
423             Note the hash functor specified for class \p Traits template parameter
424             should accept a parameter of type \p Q that may be not the same as \p value_type.
425
426             The function returns \p true if \p key is found, \p false otherwise.
427         */
428         template <typename Q, typename Func>
429         bool find( Q& key, Func f )
430         {
431             return base_class::find( key, [&f]( leaf_node& node, Q& v ) { f( node.m_Value, v ); });
432         }
433         //@cond
434         template <typename Q, typename Func>
435         bool find( Q const& key, Func f )
436         {
437             return base_class::find( key, [&f]( leaf_node& node, Q const& v ) { f( node.m_Value, v ); } );
438         }
439         //@endcond
440
441         /// Finds the key \p key using \p pred predicate for searching
442         /**
443             The function is an analog of \ref cds_nonintrusive_EllenBinTreeSet_find_func "find(Q&, Func)"
444             but \p pred is used for key comparing.
445             \p Less functor has the interface like \p std::less.
446             \p Less must imply the same element order as the comparator used for building the set.
447         */
448         template <typename Q, typename Less, typename Func>
449         bool find_with( Q& key, Less pred, Func f )
450         {
451             return base_class::find_with( key, cds::details::predicate_wrapper< leaf_node, Less, typename maker::value_accessor >(),
452                 [&f]( leaf_node& node, Q& v ) { f( node.m_Value, v ); } );
453         }
454         //@cond
455         template <typename Q, typename Less, typename Func>
456         bool find_with( Q const& key, Less pred, Func f )
457         {
458             return base_class::find_with( key, cds::details::predicate_wrapper< leaf_node, Less, typename maker::value_accessor >(),
459                                           [&f]( leaf_node& node, Q const& v ) { f( node.m_Value, v ); } );
460         }
461         //@endcond
462
463         /// Find the key \p key
464         /** @anchor cds_nonintrusive_EllenBinTreeSet_find_val
465
466             The function searches the item with key equal to \p key
467             and returns \p true if it is found, and \p false otherwise.
468
469             Note the hash functor specified for class \p Traits template parameter
470             should accept a parameter of type \p Q that may be not the same as \ref value_type.
471         */
472         template <typename Q>
473         bool find( Q const & key )
474         {
475             return base_class::find( key );
476         }
477
478         /// Finds the key \p key using \p pred predicate for searching
479         /**
480             The function is an analog of \ref cds_nonintrusive_EllenBinTreeSet_find_val "find(Q const&)"
481             but \p pred is used for key comparing.
482             \p Less functor has the interface like \p std::less.
483             \p Less must imply the same element order as the comparator used for building the set.
484         */
485         template <typename Q, typename Less>
486         bool find_with( Q const& key, Less pred )
487         {
488             return base_class::find_with( key, cds::details::predicate_wrapper< leaf_node, Less, typename maker::value_accessor >());
489         }
490
491         /// Finds \p key and returns the item found
492         /** @anchor cds_nonintrusive_EllenBinTreeSet_get
493             The function searches the item with key equal to \p key and returns the item found in \p result parameter.
494             The function returns \p true if \p key is found, \p false otherwise.
495
496             The guarded pointer \p dest prevents deallocation of returned item,
497             see cds::gc::guarded_ptr for explanation.
498             @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
499         */
500         template <typename Q>
501         bool get( guarded_ptr& result, Q const& key )
502         {
503             return base_class::get_( result.guard(), key );
504         }
505
506         /// Finds \p key with predicate \p pred and returns the item found
507         /**
508             The function is an analog of \ref cds_nonintrusive_EllenBinTreeSet_get "get(guarded_ptr&, Q const&)"
509             but \p pred is used for key comparing.
510             \p Less functor has the interface like \p std::less.
511             \p pred must imply the same element order as the comparator used for building the set.
512         */
513         template <typename Q, typename Less>
514         bool get_with( guarded_ptr& result, Q const& key, Less pred )
515         {
516             return base_class::get_with_( result.guard(), key,
517                 cds::details::predicate_wrapper< leaf_node, Less, typename maker::value_accessor >() );
518         }
519
520         /// Clears the set (not atomic)
521         /**
522             The function unlink all items from the tree.
523             The function is not atomic, thus, in multi-threaded environment with parallel insertions
524             this sequence
525             \code
526             set.clear();
527             assert( set.empty() );
528             \endcode
529             the assertion could be raised.
530
531             For each leaf the \ref disposer will be called after unlinking.
532         */
533         void clear()
534         {
535             base_class::clear();
536         }
537
538         /// Checks if the set is empty
539         bool empty() const
540         {
541             return base_class::empty();
542         }
543
544         /// Returns item count in the set
545         /**
546             Only leaf nodes containing user data are counted.
547
548             The value returned depends on item counter type provided by \p Traits template parameter.
549             If it is \p atomicity::empty_item_counter this function always returns 0.
550
551             The function is not suitable for checking the tree emptiness, use \p empty()
552             member function for this purpose.
553         */
554         size_t size() const
555         {
556             return base_class::size();
557         }
558
559         /// Returns const reference to internal statistics
560         stat const& statistics() const
561         {
562             return base_class::statistics();
563         }
564
565         /// Checks internal consistency (not atomic, not thread-safe)
566         /**
567             The debugging function to check internal consistency of the tree.
568         */
569         bool check_consistency() const
570         {
571             return base_class::check_consistency();
572         }
573     };
574
575 }} // namespace cds::container
576
577 #endif // #ifndef __CDS_CONTAINER_IMPL_ELLEN_BINTREE_SET_H