Removed unused implementation_tag typedef
[libcds.git] / cds / container / ellen_bintree_map_rcu.h
1 //$$CDS-header$$
2
3 #ifndef CDSLIB_CONTAINER_ELLEN_BINTREE_MAP_RCU_H
4 #define CDSLIB_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         typedef typename traits::back_off                   back_off;           ///< Back-off strategy
90
91         typedef typename traits::allocator                  allocator_type;        ///< Allocator for leaf nodes
92         typedef typename base_class::node_allocator         node_allocator;        ///< Internal node allocator
93         typedef typename base_class::update_desc_allocator  update_desc_allocator; ///< Update descriptor allocator
94
95         static CDS_CONSTEXPR const bool c_bExtractLockExternal = base_class::c_bExtractLockExternal; ///< Group of \p extract_xxx functions do not require external locking
96
97     protected:
98         //@cond
99         typedef typename base_class::value_type         leaf_node;
100         typedef typename base_class::internal_node      internal_node;
101         typedef typename base_class::update_desc        update_desc;
102
103         typedef typename maker::cxx_leaf_node_allocator cxx_leaf_node_allocator;
104
105         typedef std::unique_ptr< leaf_node, typename maker::leaf_deallocator >    scoped_node_ptr;
106         //@endcond
107
108     public:
109         typedef typename gc::scoped_lock    rcu_lock ;  ///< RCU scoped lock
110
111         /// pointer to extracted node
112         using exempt_ptr = cds::urcu::exempt_ptr < gc, leaf_node, value_type, typename maker::intrusive_traits::disposer,
113             cds::urcu::details::conventional_exempt_member_cast < leaf_node, value_type >
114         >;
115
116     public:
117         /// Default constructor
118         EllenBinTreeMap()
119             : base_class()
120         {}
121
122         /// Clears the map
123         ~EllenBinTreeMap()
124         {}
125
126         /// Inserts new node with key and default value
127         /**
128             The function creates a node with \p key and default value, and then inserts the node created into the map.
129
130             Preconditions:
131             - The \p key_type should be constructible from a value of type \p K.
132             - The \p mapped_type should be default-constructible.
133
134             RCU \p synchronize() can be called. RCU should not be locked.
135
136             Returns \p true if inserting successful, \p false otherwise.
137         */
138         template <typename K>
139         bool insert( K const& key )
140         {
141             return insert_with( key, [](value_type&){} );
142         }
143
144         /// Inserts new node
145         /**
146             The function creates a node with copy of \p val value
147             and then inserts the node created into the map.
148
149             Preconditions:
150             - The \p key_type should be constructible from \p key of type \p K.
151             - The \p value_type should be constructible from \p val of type \p V.
152
153             RCU \p synchronize() method can be called. RCU should not be locked.
154
155             Returns \p true if \p val is inserted into the map, \p false otherwise.
156         */
157         template <typename K, typename V>
158         bool insert( K const& key, V const& val )
159         {
160             scoped_node_ptr pNode( cxx_leaf_node_allocator().New( key, val ));
161             if ( base_class::insert( *pNode ))
162             {
163                 pNode.release();
164                 return true;
165             }
166             return false;
167         }
168
169         /// Inserts new node and initialize it by a functor
170         /**
171             This function inserts new node with key \p key and if inserting is successful then it calls
172             \p func functor with signature
173             \code
174                 struct functor {
175                     void operator()( value_type& item );
176                 };
177             \endcode
178
179             The argument \p item of user-defined functor \p func is the reference
180             to the map's item inserted:
181                 - <tt>item.first</tt> is a const reference to item's key that cannot be changed.
182                 - <tt>item.second</tt> is a reference to item's value that may be changed.
183
184             The key_type should be constructible from value of type \p K.
185
186             The function allows to split creating of new item into two part:
187             - create item from \p key;
188             - insert new item into the map;
189             - if inserting is successful, initialize the value of item by calling \p func functor
190
191             This can be useful if complete initialization of object of \p value_type is heavyweight and
192             it is preferable that the initialization should be completed only if inserting is successful.
193
194             RCU \p synchronize() method can be called. RCU should not be locked.
195         */
196         template <typename K, typename Func>
197         bool insert_with( K const& key, Func func )
198         {
199             scoped_node_ptr pNode( cxx_leaf_node_allocator().New( key ));
200             if ( base_class::insert( *pNode, [&func]( leaf_node& item ) { func( item.m_Value ); } )) {
201                 pNode.release();
202                 return true;
203             }
204             return false;
205         }
206
207         /// For key \p key inserts data of type \p value_type created in-place from \p args
208         /**
209             Returns \p true if inserting successful, \p false otherwise.
210
211             RCU \p synchronize() method can be called. RCU should not be locked.
212         */
213         template <typename K, typename... Args>
214         bool emplace( K&& key, Args&&... args )
215         {
216             scoped_node_ptr pNode( cxx_leaf_node_allocator().New( std::forward<K>(key), std::forward<Args>(args)... ));
217             if ( base_class::insert( *pNode )) {
218                 pNode.release();
219                 return true;
220             }
221             return false;
222         }
223
224         /// Updates the node
225         /**
226             The operation performs inserting or changing data with lock-free manner.
227
228             If the item \p val is not found in the map, then \p val is inserted iff \p bAllowInsert is \p true.
229             Otherwise, the functor \p func is called with item found.
230             The functor \p func signature is:
231             \code
232                 struct my_functor {
233                     void operator()( bool bNew, value_type& item );
234                 };
235             \endcode
236
237             with arguments:
238             - \p bNew - \p true if the item has been inserted, \p false otherwise
239             - \p item - item of the map
240
241             The functor may change any fields of the \p item.second that is \p mapped_type;
242             however, \p func must guarantee that during changing no any other modifications
243             could be made on this item by concurrent threads.
244
245             RCU \p synchronize() method can be called. RCU should not be locked.
246
247             Returns std::pair<bool, bool> where \p first is \p true if operation is successfull,
248             i.e. the node has been inserted or updated,
249             \p second is \p true if new item has been added or \p false if the item with \p key
250             already exists.
251
252             @warning See \ref cds_intrusive_item_creating "insert item troubleshooting"
253         */
254         template <typename K, typename Func>
255         std::pair<bool, bool> update( K const& key, Func func, bool bAllowInsert = true )
256         {
257             scoped_node_ptr pNode( cxx_leaf_node_allocator().New( key ));
258             std::pair<bool, bool> res = base_class::update( *pNode,
259                 [&func](bool bNew, leaf_node& item, leaf_node const& ){ func( bNew, item.m_Value ); },
260                 bAllowInsert
261             );
262             if ( res.first && res.second )
263                 pNode.release();
264             return res;
265         }
266         //@cond
267         // Deprecated, use update()
268         template <typename K, typename Func>
269         std::pair<bool, bool> ensure( K const& key, Func func )
270         {
271             return update( key, func, true );
272         }
273         //@endcond
274
275         /// Delete \p key from the map
276         /**\anchor cds_nonintrusive_EllenBinTreeMap_rcu_erase_val
277
278             RCU \p synchronize() method can be called. RCU should not be locked.
279
280             Return \p true if \p key is found and deleted, \p false otherwise
281         */
282         template <typename K>
283         bool erase( K const& key )
284         {
285             return base_class::erase(key);
286         }
287
288         /// Deletes the item from the map using \p pred predicate for searching
289         /**
290             The function is an analog of \ref cds_nonintrusive_EllenBinTreeMap_rcu_erase_val "erase(K const&)"
291             but \p pred is used for key comparing.
292             \p Less functor has the interface like \p std::less.
293             \p Less must imply the same element order as the comparator used for building the map.
294         */
295         template <typename K, typename Less>
296         bool erase_with( K const& key, Less pred )
297         {
298             CDS_UNUSED( pred );
299             return base_class::erase_with( key, cds::details::predicate_wrapper< leaf_node, Less, typename maker::key_accessor >());
300         }
301
302         /// Delete \p key from the map
303         /** \anchor cds_nonintrusive_EllenBinTreeMap_rcu_erase_func
304
305             The function searches an item with key \p key, calls \p f functor
306             and deletes the item. If \p key is not found, the functor is not called.
307
308             The functor \p Func interface:
309             \code
310             struct extractor {
311                 void operator()(value_type& item) { ... }
312             };
313             \endcode
314
315             RCU \p synchronize method can be called. RCU should not be locked.
316
317             Return \p true if key is found and deleted, \p false otherwise
318         */
319         template <typename K, typename Func>
320         bool erase( K const& key, Func f )
321         {
322             return base_class::erase( key, [&f]( leaf_node& node) { f( node.m_Value ); } );
323         }
324
325         /// Deletes the item from the map using \p pred predicate for searching
326         /**
327             The function is an analog of \ref cds_nonintrusive_EllenBinTreeMap_rcu_erase_func "erase(K const&, Func)"
328             but \p pred is used for key comparing.
329             \p Less functor has the interface like \p std::less.
330             \p Less must imply the same element order as the comparator used for building the map.
331         */
332         template <typename K, typename Less, typename Func>
333         bool erase_with( K const& key, Less pred, Func f )
334         {
335             CDS_UNUSED( pred );
336             return base_class::erase_with( key, cds::details::predicate_wrapper< leaf_node, Less, typename maker::key_accessor >(),
337                 [&f]( leaf_node& node) { f( node.m_Value ); } );
338         }
339
340         /// Extracts an item with minimal key from the map
341         /**
342             Returns \ref cds::urcu::exempt_ptr "exempt_ptr" pointer to the leftmost item.
343             If the set is empty, returns empty \p exempt_ptr.
344
345             @note Due the concurrent nature of the map, the function extracts <i>nearly</i> minimum key.
346             It means that the function gets leftmost leaf of the tree and tries to unlink it.
347             During unlinking, a concurrent thread may insert an item with key less than leftmost item's key.
348             So, the function returns the item with minimum key at the moment of tree traversing.
349
350             RCU \p synchronize method can be called. RCU should NOT be locked.
351             The function does not free the item.
352             The deallocator will be implicitly invoked when the returned object is destroyed or when
353             its \p release() member function is called.
354         */
355         exempt_ptr extract_min()
356         {
357             return exempt_ptr( base_class::extract_min_());
358         }
359
360         /// Extracts an item with maximal key from the map
361         /**
362             Returns \ref cds::urcu::exempt_ptr "exempt_ptr" pointer to the rightmost item.
363             If the set is empty, returns empty \p exempt_ptr.
364
365             @note Due the concurrent nature of the map, the function extracts <i>nearly</i> maximal key.
366             It means that the function gets rightmost leaf of the tree and tries to unlink it.
367             During unlinking, a concurrent thread may insert an item with key great than leftmost item's key.
368             So, the function returns the item with maximum key at the moment of tree traversing.
369
370             RCU \p synchronize method can be called. RCU should NOT be locked.
371             The function does not free the item.
372             The deallocator will be implicitly invoked when the returned object is destroyed or when
373             its \p release() is called.
374             @note Before reusing \p result object you should call its \p release() method.
375         */
376         exempt_ptr extract_max()
377         {
378             return exempt_ptr( base_class::extract_max_());
379         }
380
381         /// Extracts an item from the map
382         /** \anchor cds_nonintrusive_EllenBinTreeMap_rcu_extract
383             The function searches an item with key equal to \p key in the tree,
384             unlinks it, and returns \ref cds::urcu::exempt_ptr "exempt_ptr" pointer to an item found.
385             If \p key is not found the function returns an empty \p exempt_ptr.
386
387             RCU \p synchronize method can be called. RCU should NOT be locked.
388             The function does not destroy the item found.
389             The dealloctor will be implicitly invoked when the returned object is destroyed or when
390             its \p release() member function is called.
391         */
392         template <typename Q>
393         exempt_ptr extract( Q const& key )
394         {
395             return exempt_ptr( base_class::extract_( key, typename base_class::node_compare()));
396         }
397
398         /// Extracts an item from the map using \p pred for searching
399         /**
400             The function is an analog of \p extract(Q const&)
401             but \p pred is used for key compare.
402             \p Less has the interface like \p std::less and should meet \ref cds_container_EllenBinTreeSet_rcu_less
403             "predicate requirements".
404             \p pred must imply the same element order as the comparator used for building the map.
405         */
406         template <typename Q, typename Less>
407         exempt_ptr extract_with( Q const& key, Less pred )
408         {
409             CDS_UNUSED( pred );
410             return exempt_ptr( base_class::extract_with_( key,
411                 cds::details::predicate_wrapper< leaf_node, Less, typename maker::key_accessor >() ));
412         }
413
414         /// Find the key \p key
415         /** \anchor cds_nonintrusive_EllenBinTreeMap_rcu_find_cfunc
416
417             The function searches the item with key equal to \p key and calls the functor \p f for item found.
418             The interface of \p Func functor is:
419             \code
420             struct functor {
421                 void operator()( value_type& item );
422             };
423             \endcode
424             where \p item is the item found.
425
426             The functor may change \p item.second.
427
428             The function applies RCU lock internally.
429
430             The function returns \p true if \p key is found, \p false otherwise.
431         */
432         template <typename K, typename Func>
433         bool find( K const& key, Func f )
434         {
435             return base_class::find( key, [&f](leaf_node& item, K const& ) { f( item.m_Value );});
436         }
437
438         /// Finds the key \p val using \p pred predicate for searching
439         /**
440             The function is an analog of \ref cds_nonintrusive_EllenBinTreeMap_rcu_find_cfunc "find(K const&, Func)"
441             but \p pred is used for key comparing.
442             \p Less functor has the interface like \p std::less.
443             \p Less must imply the same element order as the comparator used for building the map.
444         */
445         template <typename K, typename Less, typename Func>
446         bool find_with( K const& key, Less pred, Func f )
447         {
448             CDS_UNUSED( pred );
449             return base_class::find_with( key, cds::details::predicate_wrapper< leaf_node, Less, typename maker::key_accessor >(),
450                 [&f](leaf_node& item, K const& ) { f( item.m_Value );});
451         }
452
453         /// Checks whether the map contains \p key
454         /**
455             The function searches the item with key equal to \p key
456             and returns \p true if it is found, and \p false otherwise.
457
458             The function applies RCU lock internally.
459         */
460         template <typename K>
461         bool contains( K const& key )
462         {
463             return base_class::contains( key );
464         }
465         //@cond
466         // Deprecated, use contains()
467         template <typename K>
468         bool find( K const& key )
469         {
470             return contains( key );
471         }
472         //@endcond
473
474         /// Checks whether the map contains \p key using \p pred predicate for searching
475         /**
476             The function is similar to <tt>contains( key )</tt> but \p pred is used for key comparing.
477             \p Less functor has the interface like \p std::less and should meet \ref cds_intrusive_EllenBinTree_rcu_less
478             "Predicate requirements".
479             \p Less must imply the same element order as the comparator used for building the set.
480         */
481         template <typename K, typename Less>
482         bool contains( K const& key, Less pred )
483         {
484             CDS_UNUSED( pred );
485             return base_class::contains( key, cds::details::predicate_wrapper< leaf_node, Less, typename maker::key_accessor >() );
486         }
487         //@cond
488         // Deprecated, use contains()
489         template <typename K, typename Less>
490         bool find_with( K const& key, Less pred )
491         {
492             return contains( key, pred );
493         }
494         //@endcond
495
496         /// Finds \p key and return the item found
497         /** \anchor cds_nonintrusive_EllenBinTreeMap_rcu_get
498             The function searches the item with key equal to \p key and returns the pointer to item found.
499             If \p key is not found it returns \p nullptr.
500
501             RCU should be locked before call the function.
502             Returned pointer is valid while RCU is locked.
503         */
504         template <typename Q>
505         value_type * get( Q const& key ) const
506         {
507             leaf_node * pNode = base_class::get( key );
508             return pNode ? &pNode->m_Value : nullptr;
509         }
510
511         /// Finds \p key with \p pred predicate and return the item found
512         /**
513             The function is an analog of \ref cds_nonintrusive_EllenBinTreeMap_rcu_get "get(Q const&)"
514             but \p pred is used for comparing the keys.
515
516             \p Less functor has the semantics like \p std::less but should take arguments of type \p key_type
517             and \p Q in any order.
518             \p pred must imply the same element order as the comparator used for building the map.
519         */
520         template <typename Q, typename Less>
521         value_type * get_with( Q const& key, Less pred ) const
522         {
523             CDS_UNUSED( pred );
524             leaf_node * pNode = base_class::get_with( key,
525                 cds::details::predicate_wrapper< leaf_node, Less, typename maker::key_accessor >());
526             return pNode ? &pNode->m_Value : nullptr;
527         }
528
529         /// Clears the map
530         void clear()
531         {
532             base_class::clear();
533         }
534
535         /// Checks if the map is empty
536         bool empty() const
537         {
538             return base_class::empty();
539         }
540
541         /// Returns item count in the map
542         /**
543             Only leaf nodes containing user data are counted.
544
545             The value returned depends on item counter type provided by \p Traits template parameter.
546             If it is \p atomicity::empty_item_counter this function always returns 0.
547
548             The function is not suitable for checking the tree emptiness, use \p empty()
549             member function for this purpose.
550         */
551         size_t size() const
552         {
553             return base_class::size();
554         }
555
556         /// Returns const reference to internal statistics
557         stat const& statistics() const
558         {
559             return base_class::statistics();
560         }
561
562         /// Checks internal consistency (not atomic, not thread-safe)
563         /**
564             The debugging function to check internal consistency of the tree.
565         */
566         bool check_consistency() const
567         {
568             return base_class::check_consistency();
569         }
570     };
571 }} // namespace cds::container
572
573 #endif //#ifndef CDSLIB_CONTAINER_ELLEN_BINTREE_MAP_RCU_H