EllenBinTree refactoring
[libcds.git] / cds / container / ellen_bintree_map_rcu.h
1 //$$CDS-header$$
2
3 #ifndef __CDS_CONTAINER_ELLEN_BINTREE_MAP_RCU_H
4 #define __CDS_CONTAINER_ELLEN_BINTREE_MAP_RCU_H
5
6 #include <cds/container/details/ellen_bintree_base.h>
7 #include <cds/intrusive/ellen_bintree_rcu.h>
8
9 namespace cds { namespace container {
10
11     /// Map based on Ellen's et al binary search tree (RCU specialization)
12     /** @ingroup cds_nonintrusive_map
13         @ingroup cds_nonintrusive_tree
14         @anchor cds_container_EllenBinTreeMap_rcu
15
16         Source:
17             - [2010] F.Ellen, P.Fatourou, E.Ruppert, F.van Breugel "Non-blocking Binary Search Tree"
18
19         %EllenBinTreeMap is an unbalanced leaf-oriented binary search tree that implements the <i>map</i>
20         abstract data type. Nodes maintains child pointers but not parent pointers.
21         Every internal node has exactly two children, and all data of type <tt>std::pair<Key const, T></tt>
22         currently in the tree are stored in the leaves. Internal nodes of the tree are used to direct \p find
23         operation along the path to the correct leaf. The keys (of \p Key type) stored in internal nodes
24         may or may not be in the map.
25         Unlike \ref cds_container_EllenBinTreeSet_rcu "EllenBinTreeSet" keys are not a part of \p T type.
26         The map can be represented as a set containing <tt>std::pair< Key const, T> </tt> values.
27
28         Due to \p extract_min and \p extract_max member functions the \p %EllenBinTreeMap can act as
29         a <i>priority queue</i>. In this case you should provide unique compound key, for example,
30         the priority value plus some uniformly distributed random value.
31
32         @warning Recall the tree is <b>unbalanced</b>. The complexity of operations is <tt>O(log N)</tt>
33         for uniformly distributed random keys, but in worst case the complexity is <tt>O(N)</tt>.
34
35         @note In the current implementation we do not use helping technique described in original paper.
36         So, the current implementation is near to fine-grained lock-based tree.
37         Helping will be implemented in future release
38
39         <b>Template arguments</b> :
40         - \p RCU - one of \ref cds_urcu_gc "RCU type"
41         - \p Key - key type
42         - \p T - value type to be stored in tree's leaf nodes.
43         - \p Traits - map traits, default is \p ellen_bintree::traits.
44             It is possible to declare option-based tree with \p ellen_bintree::make_map_traits metafunction
45             instead of \p Traits template argument.
46
47         @note Before including <tt><cds/container/ellen_bintree_map_rcu.h></tt> you should include appropriate RCU header file,
48         see \ref cds_urcu_gc "RCU type" for list of existing RCU class and corresponding header files.
49     */
50     template <
51         class RCU,
52         typename Key,
53         typename T,
54 #ifdef CDS_DOXYGEN_INVOKED
55         class Traits = ellen_bintree::traits
56 #else
57         class Traits
58 #endif
59     >
60     class EllenBinTreeMap< cds::urcu::gc<RCU>, Key, T, Traits >
61 #ifdef CDS_DOXYGEN_INVOKED
62         : public cds::intrusive::EllenBinTree< cds::urcu::gc<RCU>, Key, T, Traits >
63 #else
64         : public ellen_bintree::details::make_ellen_bintree_map< cds::urcu::gc<RCU>, Key, T, Traits >::type
65 #endif
66     {
67         //@cond
68         typedef ellen_bintree::details::make_ellen_bintree_map< cds::urcu::gc<RCU>, Key, T, Traits > maker;
69         typedef typename maker::type base_class;
70         //@endcond
71     public:
72         typedef cds::urcu::gc<RCU>  gc;   ///< RCU Garbage collector
73         typedef Key     key_type;    ///< type of a key stored in the map
74         typedef T       mapped_type; ///< type of value stored in the map
75         typedef std::pair< key_type const, mapped_type >    value_type;   ///< Key-value pair stored in leaf node of the mp
76         typedef Traits  traits;      ///< Traits template parameter
77
78 #   ifdef CDS_DOXYGEN_INVOKED
79         typedef implementation_defined key_comparator  ;    ///< key compare functor based on \p Traits::compare and \p Traits::less
80 #   else
81         typedef typename maker::intrusive_traits::compare   key_comparator;
82 #   endif
83         typedef typename base_class::item_counter           item_counter;       ///< Item counting policy
84         typedef typename base_class::memory_model           memory_model;       ///< Memory ordering, see \p cds::opt::memory_model option
85         typedef typename base_class::node_allocator         node_allocator_type; ///< allocator for maintaining internal node
86         typedef typename base_class::stat                   stat;               ///< internal statistics
87         typedef typename base_class::rcu_check_deadlock     rcu_check_deadlock; ///< Deadlock checking policy
88         typedef typename traits::copy_policy                copy_policy;        ///< key copy policy
89
90         typedef typename traits::allocator                  allocator_type;        ///< Allocator for leaf nodes
91         typedef typename base_class::node_allocator         node_allocator;        ///< Internal node allocator
92         typedef typename base_class::update_desc_allocator  update_desc_allocator; ///< Update descriptor allocator
93
94         static CDS_CONSTEXPR const bool c_bExtractLockExternal = base_class::c_bExtractLockExternal; ///< Group of \p extract_xxx functions do not require external locking
95
96     protected:
97         //@cond
98         typedef typename base_class::value_type         leaf_node;
99         typedef typename base_class::internal_node      internal_node;
100         typedef typename base_class::update_desc        update_desc;
101
102         typedef typename maker::cxx_leaf_node_allocator cxx_leaf_node_allocator;
103
104         typedef std::unique_ptr< leaf_node, typename maker::leaf_deallocator >    scoped_node_ptr;
105         //@endcond
106
107     public:
108         typedef typename gc::scoped_lock    rcu_lock ;  ///< RCU scoped lock
109
110         /// pointer to extracted node
111         typedef cds::urcu::exempt_ptr< gc, leaf_node, value_type, typename maker::intrusive_traits::disposer,
112             cds::urcu::details::conventional_exempt_member_cast<leaf_node, value_type>
113         > exempt_ptr;
114
115     public:
116         /// Default constructor
117         EllenBinTreeMap()
118             : base_class()
119         {}
120
121         /// Clears the map
122         ~EllenBinTreeMap()
123         {}
124
125         /// Inserts new node with key and default value
126         /**
127             The function creates a node with \p key and default value, and then inserts the node created into the map.
128
129             Preconditions:
130             - The \p key_type should be constructible from a value of type \p K.
131             - The \p mapped_type should be default-constructible.
132
133             RCU \p synchronize() can be called. RCU should not be locked.
134
135             Returns \p true if inserting successful, \p false otherwise.
136         */
137         template <typename K>
138         bool insert( K const& key )
139         {
140             return insert_key( key, [](value_type&){} );
141         }
142
143         /// Inserts new node
144         /**
145             The function creates a node with copy of \p val value
146             and then inserts the node created into the map.
147
148             Preconditions:
149             - The \p key_type should be constructible from \p key of type \p K.
150             - The \p value_type should be constructible from \p val of type \p V.
151
152             RCU \p synchronize() method can be called. RCU should not be locked.
153
154             Returns \p true if \p val is inserted into the map, \p false otherwise.
155         */
156         template <typename K, typename V>
157         bool insert( K const& key, V const& val )
158         {
159             scoped_node_ptr pNode( cxx_leaf_node_allocator().New( key, val ));
160             if ( base_class::insert( *pNode ))
161             {
162                 pNode.release();
163                 return true;
164             }
165             return false;
166         }
167
168         /// Inserts new node and initialize it by a functor
169         /**
170             This function inserts new node with key \p key and if inserting is successful then it calls
171             \p func functor with signature
172             \code
173                 struct functor {
174                     void operator()( value_type& item );
175                 };
176             \endcode
177
178             The argument \p item of user-defined functor \p func is the reference
179             to the map's item inserted:
180                 - <tt>item.first</tt> is a const reference to item's key that cannot be changed.
181                 - <tt>item.second</tt> is a reference to item's value that may be changed.
182
183             The key_type should be constructible from value of type \p K.
184
185             The function allows to split creating of new item into two part:
186             - create item from \p key;
187             - insert new item into the map;
188             - if inserting is successful, initialize the value of item by calling \p func functor
189
190             This can be useful if complete initialization of object of \p value_type is heavyweight and
191             it is preferable that the initialization should be completed only if inserting is successful.
192
193             RCU \p synchronize() method can be called. RCU should not be locked.
194         */
195         template <typename K, typename Func>
196         bool insert_key( const K& key, Func func )
197         {
198             scoped_node_ptr pNode( cxx_leaf_node_allocator().New( key ));
199             if ( base_class::insert( *pNode, [&func]( leaf_node& item ) { func( item.m_Value ); } )) {
200                 pNode.release();
201                 return true;
202             }
203             return false;
204         }
205
206         /// For key \p key inserts data of type \p value_type created in-place from \p args
207         /**
208             Returns \p true if inserting successful, \p false otherwise.
209
210             RCU \p synchronize() method can be called. RCU should not be locked.
211         */
212         template <typename K, typename... Args>
213         bool emplace( K&& key, Args&&... args )
214         {
215             scoped_node_ptr pNode( cxx_leaf_node_allocator().New( std::forward<K>(key), std::forward<Args>(args)... ));
216             if ( base_class::insert( *pNode )) {
217                 pNode.release();
218                 return true;
219             }
220             return false;
221         }
222
223         /// Ensures that the \p key exists in the map
224         /**
225             The operation performs inserting or changing data with lock-free manner.
226
227             If the \p key not found in the map, then the new item created from \p key
228             is inserted into the map (note that in this case the \ref key_type should be
229             constructible from type \p K).
230             Otherwise, the functor \p func is called with item found.
231             The functor \p Func may be a function with signature:
232             \code
233                 void func( bool bNew, value_type& item );
234             \endcode
235             or a functor:
236             \code
237                 struct my_functor {
238                     void operator()( bool bNew, value_type& item );
239                 };
240             \endcode
241
242             with arguments:
243             - \p bNew - \p true if the item has been inserted, \p false otherwise
244             - \p item - item of the list
245
246             The functor may change any fields of the \p item.second that is \ref value_type.
247
248             RCU \p synchronize() method can be called. RCU should not be locked.
249
250             Returns <tt> std::pair<bool, bool> </tt> where \p first is true if operation is successfull,
251             \p second is true if new item has been added or \p false if the item with \p key
252             already is in the list.
253
254             @warning See \ref cds_intrusive_item_creating "insert item troubleshooting"
255         */
256         template <typename K, typename Func>
257         std::pair<bool, bool> ensure( K const& key, Func func )
258         {
259             scoped_node_ptr pNode( cxx_leaf_node_allocator().New( key ));
260             std::pair<bool, bool> res = base_class::ensure( *pNode,
261                 [&func](bool bNew, leaf_node& item, leaf_node const& ){ func( bNew, item.m_Value ); }
262             );
263             if ( res.first && res.second )
264                 pNode.release();
265             return res;
266         }
267
268         /// Delete \p key from the map
269         /**\anchor cds_nonintrusive_EllenBinTreeMap_rcu_erase_val
270
271             RCU \p synchronize() method can be called. RCU should not be locked.
272
273             Return \p true if \p key is found and deleted, \p false otherwise
274         */
275         template <typename K>
276         bool erase( K const& key )
277         {
278             return base_class::erase(key);
279         }
280
281         /// Deletes the item from the map using \p pred predicate for searching
282         /**
283             The function is an analog of \ref cds_nonintrusive_EllenBinTreeMap_rcu_erase_val "erase(K const&)"
284             but \p pred is used for key comparing.
285             \p Less functor has the interface like \p std::less.
286             \p Less must imply the same element order as the comparator used for building the map.
287         */
288         template <typename K, typename Less>
289         bool erase_with( K const& key, Less pred )
290         {
291             return base_class::erase_with( key, cds::details::predicate_wrapper< leaf_node, Less, typename maker::key_accessor >());
292         }
293
294         /// Delete \p key from the map
295         /** \anchor cds_nonintrusive_EllenBinTreeMap_rcu_erase_func
296
297             The function searches an item with key \p key, calls \p f functor
298             and deletes the item. If \p key is not found, the functor is not called.
299
300             The functor \p Func interface:
301             \code
302             struct extractor {
303                 void operator()(value_type& item) { ... }
304             };
305             \endcode
306
307             RCU \p synchronize method can be called. RCU should not be locked.
308
309             Return \p true if key is found and deleted, \p false otherwise
310         */
311         template <typename K, typename Func>
312         bool erase( K const& key, Func f )
313         {
314             return base_class::erase( key, [&f]( leaf_node& node) { f( node.m_Value ); } );
315         }
316
317         /// Deletes the item from the map using \p pred predicate for searching
318         /**
319             The function is an analog of \ref cds_nonintrusive_EllenBinTreeMap_rcu_erase_func "erase(K const&, Func)"
320             but \p pred is used for key comparing.
321             \p Less functor has the interface like \p std::less.
322             \p Less must imply the same element order as the comparator used for building the map.
323         */
324         template <typename K, typename Less, typename Func>
325         bool erase_with( K const& key, Less pred, Func f )
326         {
327             return base_class::erase_with( key, cds::details::predicate_wrapper< leaf_node, Less, typename maker::key_accessor >(),
328                 [&f]( leaf_node& node) { f( node.m_Value ); } );
329         }
330
331         /// Extracts an item with minimal key from the map
332         /**
333             If the map is not empty, the function returns \p true, \p result contains a pointer to value.
334             If the map is empty, the function returns \p false, \p result is left unchanged.
335
336             @note Due the concurrent nature of the map, the function extracts <i>nearly</i> minimum key.
337             It means that the function gets leftmost leaf of the tree and tries to unlink it.
338             During unlinking, a concurrent thread may insert an item with key less than leftmost item's key.
339             So, the function returns the item with minimum key at the moment of tree traversing.
340
341             RCU \p synchronize method can be called. RCU should NOT be locked.
342             The function does not free the item.
343             The deallocator will be implicitly invoked when \p result object is destroyed or when
344             <tt>result.release()</tt> is called, see cds::urcu::exempt_ptr for explanation.
345             @note Before reusing \p result object you should call its \p release() method.
346         */
347         bool extract_min( exempt_ptr& result )
348         {
349             return base_class::extract_min_( result );
350         }
351
352         /// Extracts an item with maximal key from the map
353         /**
354             If the map is not empty, the function returns \p true, \p result contains a pointer to extracted item.
355             If the map is empty, the function returns \p false, \p result is left unchanged.
356
357             @note Due the concurrent nature of the map, the function extracts <i>nearly</i> maximal key.
358             It means that the function gets rightmost leaf of the tree and tries to unlink it.
359             During unlinking, a concurrent thread may insert an item with key great than leftmost item's key.
360             So, the function returns the item with maximum key at the moment of tree traversing.
361
362             RCU \p synchronize method can be called. RCU should NOT be locked.
363             The function does not free the item.
364             The deallocator will be implicitly invoked when \p result object is destroyed or when
365             <tt>result.release()</tt> is called, see cds::urcu::exempt_ptr for explanation.
366             @note Before reusing \p result object you should call its \p release() method.
367         */
368         bool extract_max( exempt_ptr& result )
369         {
370             return base_class::extract_max_( result );
371         }
372
373         /// Extracts an item from the map
374         /** \anchor cds_nonintrusive_EllenBinTreeMap_rcu_extract
375             The function searches an item with key equal to \p key in the tree,
376             unlinks it, and returns pointer to an item found in \p result parameter.
377             If \p key is not found the function returns \p false.
378
379             RCU \p synchronize method can be called. RCU should NOT be locked.
380             The function does not destroy the item found.
381             The dealloctor will be implicitly invoked when \p result object is destroyed or when
382             <tt>result.release()</tt> is called, see cds::urcu::exempt_ptr for explanation.
383             @note Before reusing \p result object you should call its \p release() method.
384         */
385         template <typename Q>
386         bool extract( exempt_ptr& result, Q const& key )
387         {
388             return base_class::extract_( result, key, typename base_class::node_compare());
389         }
390
391         /// Extracts an item from the map using \p pred for searching
392         /**
393             The function is an analog of \ref cds_nonintrusive_EllenBinTreeMap_rcu_extract "extract(exempt_ptr&, Q const&)"
394             but \p pred is used for key compare.
395             \p Less has the interface like \p std::less and should meet \ref cds_container_EllenBinTreeSet_rcu_less
396             "predicate requirements".
397             \p pred must imply the same element order as the comparator used for building the map.
398         */
399         template <typename Q, typename Less>
400         bool extract_with( exempt_ptr& result,  Q const& val, Less pred )
401         {
402             return base_class::extract_with_( result, val,
403                 cds::details::predicate_wrapper< leaf_node, Less, typename maker::key_accessor >() );
404         }
405
406         /// Find the key \p key
407         /** \anchor cds_nonintrusive_EllenBinTreeMap_rcu_find_cfunc
408
409             The function searches the item with key equal to \p key and calls the functor \p f for item found.
410             The interface of \p Func functor is:
411             \code
412             struct functor {
413                 void operator()( value_type& item );
414             };
415             \endcode
416             where \p item is the item found.
417
418             The functor may change \p item.second.
419
420             The function applies RCU lock internally.
421
422             The function returns \p true if \p key is found, \p false otherwise.
423         */
424         template <typename K, typename Func>
425         bool find( K const& key, Func f )
426         {
427             return base_class::find( key, [&f](leaf_node& item, K const& ) { f( item.m_Value );});
428         }
429
430         /// Finds the key \p val using \p pred predicate for searching
431         /**
432             The function is an analog of \ref cds_nonintrusive_EllenBinTreeMap_rcu_find_cfunc "find(K const&, Func)"
433             but \p pred is used for key comparing.
434             \p Less functor has the interface like \p std::less.
435             \p Less must imply the same element order as the comparator used for building the map.
436         */
437         template <typename K, typename Less, typename Func>
438         bool find_with( K const& key, Less pred, Func f )
439         {
440             return base_class::find_with( key, cds::details::predicate_wrapper< leaf_node, Less, typename maker::key_accessor >(),
441                 [&f](leaf_node& item, K const& ) { f( item.m_Value );});
442         }
443
444         /// Find the key \p key
445         /** \anchor cds_nonintrusive_EllenBinTreeMap_rcu_find_val
446
447             The function searches the item with key equal to \p key
448             and returns \p true if it is found, and \p false otherwise.
449
450             The function applies RCU lock internally.
451         */
452         template <typename K>
453         bool find( K const& key )
454         {
455             return base_class::find( key );
456         }
457
458         /// Finds the key \p val using \p pred predicate for searching
459         /**
460             The function is an analog of \ref cds_nonintrusive_EllenBinTreeMap_rcu_find_val "find(K const&)"
461             but \p pred is used for key comparing.
462             \p Less functor has the interface like \p std::less.
463             \p Less must imply the same element order as the comparator used for building the map.
464         */
465         template <typename K, typename Less>
466         bool find_with( K const& key, Less pred )
467         {
468             return base_class::find_with( key, cds::details::predicate_wrapper< leaf_node, Less, typename maker::key_accessor >() );
469         }
470
471         /// Finds \p key and return the item found
472         /** \anchor cds_nonintrusive_EllenBinTreeMap_rcu_get
473             The function searches the item with key equal to \p key and returns the pointer to item found.
474             If \p key is not found it returns \p nullptr.
475
476             RCU should be locked before call the function.
477             Returned pointer is valid while RCU is locked.
478         */
479         template <typename Q>
480         value_type * get( Q const& key ) const
481         {
482             leaf_node * pNode = base_class::get( key );
483             return pNode ? &pNode->m_Value : nullptr;
484         }
485
486         /// Finds \p key with \p pred predicate and return the item found
487         /**
488             The function is an analog of \ref cds_nonintrusive_EllenBinTreeMap_rcu_get "get(Q const&)"
489             but \p pred is used for comparing the keys.
490
491             \p Less functor has the semantics like \p std::less but should take arguments of type \ref value_type
492             and \p Q in any order.
493             \p pred must imply the same element order as the comparator used for building the map.
494         */
495         template <typename Q, typename Less>
496         value_type * get_with( Q const& key, Less pred ) const
497         {
498             leaf_node * pNode = base_class::get_with( key,
499                 cds::details::predicate_wrapper< leaf_node, Less, typename maker::key_accessor >());
500             return pNode ? &pNode->m_Value : nullptr;
501         }
502
503         /// Clears the map
504         void clear()
505         {
506             base_class::clear();
507         }
508
509         /// Checks if the map is empty
510         bool empty() const
511         {
512             return base_class::empty();
513         }
514
515         /// Returns item count in the map
516         /**
517             Only leaf nodes containing user data are counted.
518
519             The value returned depends on item counter type provided by \p Traits template parameter.
520             If it is \p atomicity::empty_item_counter this function always returns 0.
521
522             The function is not suitable for checking the tree emptiness, use \p empty()
523             member function for this purpose.
524         */
525         size_t size() const
526         {
527             return base_class::size();
528         }
529
530         /// Returns const reference to internal statistics
531         stat const& statistics() const
532         {
533             return base_class::statistics();
534         }
535
536         /// Checks internal consistency (not atomic, not thread-safe)
537         /**
538             The debugging function to check internal consistency of the tree.
539         */
540         bool check_consistency() const
541         {
542             return base_class::check_consistency();
543         }
544     };
545 }} // namespace cds::container
546
547 #endif //#ifndef __CDS_CONTAINER_ELLEN_BINTREE_MAP_RCU_H