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