On dev: bronson-unit-test
[libcds.git] / cds / container / bronson_avltree_map_rcu.h
1 //$$CDS-header$$
2
3 #ifndef CDSLIB_CONTAINER_BRONSON_AVLTREE_MAP_RCU_H
4 #define CDSLIB_CONTAINER_BRONSON_AVLTREE_MAP_RCU_H
5
6 #include <cds/container/impl/bronson_avltree_map_rcu.h>
7
8 namespace cds { namespace container {
9
10     namespace bronson_avltree {
11         //@cond
12         namespace details {
13             template < class RCU, typename Key, typename T, typename Traits>
14             struct make_map
15             {
16                 typedef Key key_type;
17                 typedef T mapped_type;
18                 typedef Traits original_traits;
19
20                 typedef cds::details::Allocator< mapped_type, typename original_traits::allocator > cxx_allocator;
21
22                 struct traits : public original_traits
23                 {
24                     struct disposer {
25                         void operator()( mapped_type * p ) const
26                         {
27                             cxx_allocator().Delete( p );
28                         }
29                     };
30                 };
31
32                 // Metafunction result
33                 typedef BronsonAVLTreeMap< RCU, Key, mapped_type *, traits > type;
34             };
35         } // namespace details
36         //@endcond
37     } // namespace bronson_avltree
38
39     /// Bronson et al AVL-tree (RCU specialization)
40     /** @ingroup cds_nonintrusive_map
41         @ingroup cds_nonintrusive_tree
42         @anchor cds_container_BronsonAVLTreeMap_rcu
43
44         Source:
45             - [2010] N.Bronson, J.Casper, H.Chafi, K.Olukotun "A Practical Concurrent Binary Search Tree"
46
47         bla-bla-bla
48
49         <b>Template arguments</b>:
50         - \p RCU - one of \ref cds_urcu_gc "RCU type"
51         - \p Key - key type
52         - \p T - value type to be stored in tree's nodes.
53         - \p Traits - tree traits, default is \p bronson_avltree::traits
54             It is possible to declare option-based tree with \p bronson_avltree::make_traits metafunction
55             instead of \p Traits template argument.
56
57         @note Before including <tt><cds/container/bronson_avltree_map_rcu.h></tt> you should include appropriate RCU header file,
58         see \ref cds_urcu_gc "RCU type" for list of existing RCU class and corresponding header files.
59     */
60     template <
61         typename RCU,
62         typename Key,
63         typename T,
64 #   ifdef CDS_DOXYGEN_INVOKED
65         typename Traits = bronson_avltree::traits
66 #else
67         typename Traits
68 #endif
69     >
70     class BronsonAVLTreeMap< cds::urcu::gc<RCU>, Key, T, Traits >
71 #ifdef CDS_DOXYGEN_INVOKED
72         : private BronsonAVLTreeMap< cds::urcu::gc<RCU>, Key, T*, Traits >
73 #else
74         : private bronson_avltree::details::make_map< cds::urcu::gc<RCU>, Key, T, Traits >::type
75 #endif
76     {
77         //@cond
78         typedef bronson_avltree::details::make_map< cds::urcu::gc<RCU>, Key, T, Traits > maker;
79         typedef typename maker::type base_class;
80         //@endcond
81
82     public:
83         typedef cds::urcu::gc<RCU>  gc;   ///< RCU Garbage collector
84         typedef Key     key_type;    ///< type of a key stored in the map
85         typedef T       mapped_type; ///< type of value stored in the map
86         typedef Traits  traits;      ///< Traits template parameter
87
88         typedef typename base_class::key_comparator     key_comparator;     ///< key compare functor based on \p Traits::compare and \p Traits::less
89         typedef typename traits::item_counter           item_counter;       ///< Item counting policy
90         typedef typename traits::memory_model           memory_model;       ///< Memory ordering, see \p cds::opt::memory_model option
91         typedef typename traits::allocator              allocator_type;     ///< allocator for value
92         typedef typename traits::node_allocator         node_allocator_type;///< allocator for maintaining internal nodes
93         typedef typename traits::stat                   stat;               ///< internal statistics
94         typedef typename traits::rcu_check_deadlock     rcu_check_deadlock; ///< Deadlock checking policy
95         typedef typename traits::back_off               back_off;           ///< Back-off strategy
96         typedef typename traits::sync_monitor           sync_monitor;       ///< @ref cds_sync_monitor "Synchronization monitor" type for node-level locking
97
98         /// Enabled or disabled @ref bronson_avltree::relaxed_insert "relaxed insertion"
99         static bool const c_bRelaxedInsert = traits::relaxed_insert;
100
101         /// Group of \p extract_xxx functions does not require external locking
102         static CDS_CONSTEXPR const bool c_bExtractLockExternal = base_class::c_bExtractLockExternal;
103
104         typedef typename base_class::rcu_lock   rcu_lock;  ///< RCU scoped lock
105
106         /// Returned pointer to \p mapped_type of extracted node
107         typedef typename base_class::exempt_ptr exempt_ptr;
108
109     protected:
110         //@cond
111         typedef typename base_class::node_type        node_type;
112         typedef typename base_class::node_scoped_lock node_scoped_lock;
113         typedef typename maker::cxx_allocator         cxx_allocator;
114
115         typedef typename base_class::update_flags update_flags;
116         //@endcond
117
118     public:
119         /// Creates empty map
120         BronsonAVLTreeMap()
121         {}
122
123         /// Destroys the map
124         ~BronsonAVLTreeMap()
125         {}
126
127         /// Inserts new node with \p key and default value
128         /**
129             The function creates a node with \p key and default value, and then inserts the node created into the map.
130
131             Preconditions:
132             - The \p key_type should be constructible from a value of type \p K.
133             - The \p mapped_type should be default-constructible.
134
135             RCU \p synchronize() can be called. RCU should not be locked.
136
137             Returns \p true if inserting successful, \p false otherwise.
138         */
139         template <typename K>
140         bool insert( K const& key )
141         {
142             return base_class::do_update(key, key_comparator(),
143                 []( node_type * pNode ) -> mapped_type*
144                 {
145                     assert( pNode->m_pValue.load( memory_model::memory_order_relaxed ) == nullptr );
146                     CDS_UNUSED( pNode );
147                     return cxx_allocator().New();
148                 },
149                 update_flags::allow_insert
150             ) == update_flags::result_inserted;
151         }
152
153         /// Inserts new node
154         /**
155             The function creates a node with copy of \p val value
156             and then inserts the node created into the map.
157
158             Preconditions:
159             - The \p key_type should be constructible from \p key of type \p K.
160             - The \p mapped_type should be constructible from \p val of type \p V.
161
162             RCU \p synchronize() method can be called. RCU should not be locked.
163
164             Returns \p true if \p val is inserted into the map, \p false otherwise.
165         */
166         template <typename K, typename V>
167         bool insert( K const& key, V const& val )
168         {
169             return base_class::do_update( key, key_comparator(),
170                 [&val]( node_type * pNode ) -> mapped_type*
171                 {
172                     assert( pNode->m_pValue.load( memory_model::memory_order_relaxed ) == nullptr );
173                     CDS_UNUSED( pNode );
174                     return cxx_allocator().New( val );
175                 },
176                 update_flags::allow_insert
177             ) == update_flags::result_inserted;
178         }
179
180         /// Inserts new node and initialize it by a functor
181         /**
182             This function inserts new node with key \p key and if inserting is successful then it calls
183             \p func functor with signature
184             \code
185                 struct functor {
186                     void operator()( key_type const& key, mapped_type& item );
187                 };
188             \endcode
189
190             The key_type should be constructible from value of type \p K.
191
192             The function allows to split creating of new item into two part:
193             - create item from \p key;
194             - insert new item into the map;
195             - if inserting is successful, initialize the value of item by calling \p func functor
196
197             This can be useful if complete initialization of object of \p value_type is heavyweight and
198             it is preferable that the initialization should be completed only if inserting is successful.
199             The functor is called under the node lock.
200
201             RCU \p synchronize() method can be called. RCU should not be locked.
202         */
203         template <typename K, typename Func>
204         bool insert_with( K const& key, Func func )
205         {
206             return base_class::do_update( key, key_comparator(),
207                 [&func]( node_type * pNode ) -> mapped_type*
208                 {
209                     assert( pNode->m_pValue.load( memory_model::memory_order_relaxed ) == nullptr );
210                     mapped_type * pVal = cxx_allocator().New();
211                     func( pNode->m_key, *pVal );
212                     return pVal;
213                 },
214                 update_flags::allow_insert
215             ) == update_flags::result_inserted;
216         }
217
218         /// For key \p key inserts data of type \p mapped_type created in-place from \p args
219         /**
220             Returns \p true if inserting successful, \p false otherwise.
221
222             RCU \p synchronize() method can be called. RCU should not be locked.
223         */
224         template <typename K, typename... Args>
225         bool emplace( K&& key, Args&&... args )
226         {
227             return base_class::do_update( key, key_comparator(),
228                 [&]( node_type * pNode ) -> mapped_type* 
229                 {
230                     assert( pNode->m_pValue.load( memory_model::memory_order_relaxed ) == nullptr );
231                     CDS_UNUSED( pNode );
232                     return cxx_allocator().New( std::forward<Args>(args)...);
233                 },
234                 update_flags::allow_insert
235             ) == update_flags::result_inserted;
236         }
237
238         /// Ensures that the \p key exists in the map
239         /**
240             The operation performs inserting or changing data with lock-free manner.
241
242             If the \p key not found in the map, then the new item created from \p key
243             will be inserted into the map (note that in this case the \ref key_type should be
244             constructible from type \p K).
245             Otherwise, the functor \p func is called with item found.
246             The functor \p Func may be a functor:
247             \code
248                 struct my_functor {
249                     void operator()( bool bNew, key_type const& key, mapped_type& item );
250                 };
251             \endcode
252
253             with arguments:
254             - \p bNew - \p true if the item has been inserted, \p false otherwise
255             - \p item - value
256
257             The functor may change any fields of the \p item. The functor is called under the node lock.
258
259             RCU \p synchronize() method can be called. RCU should not be locked.
260
261             Returns <tt> std::pair<bool, bool> </tt> where \p first is \p true if operation is successfull,
262             \p second is \p true if new item has been added or \p false if the item with \p key
263             already exists.
264         */
265         template <typename K, typename Func>
266         std::pair<bool, bool> update( K const& key, Func func )
267         {
268             int result = base_class::do_update( key, key_comparator(),
269                 [&func]( node_type * pNode ) -> mapped_type* 
270                 {
271                     mapped_type * pVal = pNode->m_pValue.load( memory_model::memory_order_relaxed );
272                     if ( !pVal ) {
273                         pVal = cxx_allocator().New();
274                         func( true, pNode->m_key, *pVal );
275                     }
276                     else
277                         func( false, pNode->m_key, *pVal );
278                     return pVal;
279                 },
280                 update_flags::allow_insert | update_flags::allow_update 
281             );
282             return std::make_pair( result != 0, (result & update_flags::result_inserted) != 0 );
283         }
284
285         //@cond
286         template <typename K, typename Func>
287         std::pair<bool, bool> ensure( K const& key, Func func )
288         {
289             return update( key, func );
290         }
291         //@endcond
292
293
294         /// Delete \p key from the map
295         /**
296             RCU \p synchronize() method can be called. RCU should not be locked.
297
298             Return \p true if \p key is found and deleted, \p false otherwise
299         */
300         template <typename K>
301         bool erase( K const& key )
302         {
303             return base_class::erase( key );
304         }
305
306         /// Deletes the item from the map using \p pred predicate for searching
307         /**
308             The function is an analog of \p erase(K const&)
309             but \p pred is used for key comparing.
310             \p Less functor has the interface like \p std::less.
311             \p Less must imply the same element order as the comparator used for building the map.
312         */
313         template <typename K, typename Less>
314         bool erase_with( K const& key, Less pred )
315         {
316             return base_class::erase_with( key, pred );
317         }
318
319         /// Delete \p key from the map
320         /** \anchor cds_nonintrusive_BronsonAVLTreeMap_rcu_erase_func
321
322             The function searches an item with key \p key, calls \p f functor
323             and deletes the item. If \p key is not found, the functor is not called.
324
325             The functor \p Func interface:
326             \code
327             struct extractor {
328                 void operator()(mapped_type& item) { ... }
329             };
330             \endcode
331
332             RCU \p synchronize method can be called. RCU should not be locked.
333
334             Return \p true if key is found and deleted, \p false otherwise
335         */
336         template <typename K, typename Func>
337         bool erase( K const& key, Func f )
338         {
339             return base_class::erase( key, f );
340         }
341
342         /// Deletes the item from the map using \p pred predicate for searching
343         /**
344             The function is an analog of \ref cds_nonintrusive_BronsonAVLTreeMap_rcu_erase_func "erase(K const&, Func)"
345             but \p pred is used for key comparing.
346             \p Less functor has the interface like \p std::less.
347             \p Less must imply the same element order as the comparator used for building the map.
348         */
349         template <typename K, typename Less, typename Func>
350         bool erase_with( K const& key, Less pred, Func f )
351         {
352             return base_class::erase_with( key, pred, f );
353         }
354
355         /// Extracts a value with minimal key from the map
356         /**
357             Returns \p exempt_ptr pointer to the leftmost item.
358             If the set is empty, returns empty \p exempt_ptr.
359
360             Note that the function returns only the value for minimal key.
361             To retrieve its key use \p extract_min( Func ) member function.
362
363             @note Due the concurrent nature of the map, the function extracts <i>nearly</i> minimum key.
364             It means that the function gets leftmost leaf of the tree and tries to unlink it.
365             During unlinking, a concurrent thread may insert an item with key less than leftmost item's key.
366             So, the function returns the item with minimum 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() member function is called.
372         */
373         exempt_ptr extract_min()
374         {
375             return base_class::extract_min();
376         }
377
378         /// Extracts minimal key key and corresponding value
379         /**
380             Returns \p exempt_ptr to the leftmost item.
381             If the tree is empty, returns empty \p exempt_ptr.
382
383             \p Func functor is used to store minimal key.
384             \p Func has the following signature:
385             \code
386                 struct functor {
387                     void operator()( key_type const& key );
388                 };
389             \endcode
390             If the tree is empty, \p f is not called.
391             Otherwise, is it called with minimal key, the pointer to corresponding value is returned
392             as \p exempt_ptr.
393
394             @note Due the concurrent nature of the map, the function extracts <i>nearly</i> minimum key.
395             It means that the function gets leftmost leaf of the tree and tries to unlink it.
396             During unlinking, a concurrent thread may insert an item with key less than leftmost item's key.
397             So, the function returns the item with minimum key at the moment of tree traversing.
398
399             RCU \p synchronize method can be called. RCU should NOT be locked.
400             The function does not free the item.
401             The deallocator will be implicitly invoked when the returned object is destroyed or when
402             its \p release() member function is called.
403         */
404         template <typename Func>
405         exempt_ptr extract_min( Func f )
406         {
407             return base_class::extract_min( f );
408         }
409
410         /// Extracts minimal key key and corresponding value
411         /**
412             This function is a shortcut for the following call:
413             \code
414                 key_type key;
415                 exempt_ptr xp = theTree.extract_min( [&key]( key_type const& k ) { key = k; } );
416             \endode
417             \p key_type should be copy-assignable. The copy of minimal key
418             is returned in \p min_key argument.
419         */
420         typename std::enable_if< std::is_copy_assignable<key_type>::value, exempt_ptr >::type
421         extract_min_key( key_type& min_key )
422         {
423             return base_class::extract_min_key( min_key );
424         }
425
426         /// Extracts an item with maximal key from the map
427         /**
428             Returns \p exempt_ptr pointer to the rightmost item.
429             If the set is empty, returns empty \p exempt_ptr.
430
431             Note that the function returns only the value for maximal key.
432             To retrieve its key use \p extract_max( Func ) member function.
433
434             @note Due the concurrent nature of the map, the function extracts <i>nearly</i> maximal key.
435             It means that the function gets rightmost leaf of the tree and tries to unlink it.
436             During unlinking, a concurrent thread may insert an item with key great than leftmost item's key.
437             So, the function returns the item with maximum key at the moment of tree traversing.
438
439             RCU \p synchronize method can be called. RCU should NOT be locked.
440             The function does not free the item.
441             The deallocator will be implicitly invoked when the returned object is destroyed or when
442             its \p release() is called.
443         */
444         exempt_ptr extract_max()
445         {
446             return base_class::extract_max();
447         }
448
449         /// Extracts the maximal key and corresponding value
450         /**
451             Returns \p exempt_ptr pointer to the rightmost item.
452             If the set is empty, returns empty \p exempt_ptr.
453
454             \p Func functor is used to store maximal key.
455             \p Func has the following signature:
456             \code
457                 struct functor {
458                     void operator()( key_type const& key );
459                 };
460             \endcode
461             If the tree is empty, \p f is not called.
462             Otherwise, is it called with maximal key, the pointer to corresponding value is returned
463             as \p exempt_ptr.
464
465             @note Due the concurrent nature of the map, the function extracts <i>nearly</i> maximal key.
466             It means that the function gets rightmost leaf of the tree and tries to unlink it.
467             During unlinking, a concurrent thread may insert an item with key great than leftmost item's key.
468             So, the function returns the item with maximum key at the moment of tree traversing.
469
470             RCU \p synchronize method can be called. RCU should NOT be locked.
471             The function does not free the item.
472             The deallocator will be implicitly invoked when the returned object is destroyed or when
473             its \p release() is called.
474         */
475         template <typename Func>
476         exempt_ptr extract_max( Func f )
477         {
478             return base_class::extract_max( f );
479         }
480
481         /// Extracts the maximal key and corresponding value
482         /**
483             This function is a shortcut for the following call:
484             \code
485                 key_type key;
486                 exempt_ptr xp = theTree.extract_max( [&key]( key_type const& k ) { key = k; } );
487             \endode
488             \p key_type should be copy-assignable. The copy of maximal key
489             is returned in \p max_key argument.
490         */
491         typename std::enable_if< std::is_copy_assignable<key_type>::value, exempt_ptr >::type
492         extract_max_key( key_type& max_key )
493         {
494             return base_class::extract_max_key( max_key );
495         }
496
497         /// Extracts an item from the map
498         /**
499             The function searches an item with key equal to \p key in the tree,
500             unlinks it, and returns \p exempt_ptr pointer to a value found.
501             If \p key is not found the function returns an empty \p exempt_ptr.
502
503             RCU \p synchronize method can be called. RCU should NOT be locked.
504             The function does not destroy the value found.
505             The dealloctor will be implicitly invoked when the returned object is destroyed or when
506             its \p release() member function is called.
507         */
508         template <typename Q>
509         exempt_ptr extract( Q const& key )
510         {
511             return base_class::extract( key );
512         }
513
514         /// Extracts an item from the map using \p pred for searching
515         /**
516             The function is an analog of \p extract(Q const&)
517             but \p pred is used for key compare.
518             \p Less has the interface like \p std::less.
519             \p pred must imply the same element order as the comparator used for building the map.
520         */
521         template <typename Q, typename Less>
522         exempt_ptr extract_with( Q const& key, Less pred )
523         {
524             return base_class::extract_with( key, pred );
525         }
526
527         /// Find the key \p key
528         /**
529             The function searches the item with key equal to \p key and calls the functor \p f for item found.
530             The interface of \p Func functor is:
531             \code
532             struct functor {
533                 void operator()( key_type const& key, mapped_type& val );
534             };
535             \endcode
536             where \p val is the item found for \p key
537             The functor is called under node-level lock.
538
539             The function applies RCU lock internally.
540
541             The function returns \p true if \p key is found, \p false otherwise.
542         */
543         template <typename K, typename Func>
544         bool find( K const& key, Func f )
545         {
546             return base_class::find( key, f );
547         }
548
549         /// Finds the key \p val using \p pred predicate for searching
550         /**
551             The function is an analog of \p find(K const&, Func)
552             but \p pred is used for key comparing.
553             \p Less functor has the interface like \p std::less.
554             \p Less must imply the same element order as the comparator used for building the map.
555         */
556         template <typename K, typename Less, typename Func>
557         bool find_with( K const& key, Less pred, Func f )
558         {
559             return base_class::find_with( key, pred, f );
560         }
561
562         /// Find the key \p key
563         /**
564             The function searches the item with key equal to \p key
565             and returns \p true if it is found, and \p false otherwise.
566
567             The function applies RCU lock internally.
568         */
569         template <typename K>
570         bool find( K const& key )
571         {
572             return base_class::find( key );
573         }
574
575         /// Finds the key \p val using \p pred predicate for searching
576         /**
577             The function is an analog of \p find(K const&)
578             but \p pred is used for key comparing.
579             \p Less functor has the interface like \p std::less.
580             \p Less must imply the same element order as the comparator used for building the map.
581         */
582         template <typename K, typename Less>
583         bool find_with( K const& key, Less pred )
584         {
585             return base_class::find_with( key, pred );
586         }
587
588         /// Clears the map
589         void clear()
590         {
591             base_class::clear();
592         }
593
594         /// Checks if the map is empty
595         bool empty() const
596         {
597             return base_class::empty();
598         }
599
600         /// Returns item count in the map
601         /**
602             Only leaf nodes containing user data are counted.
603
604             The value returned depends on item counter type provided by \p Traits template parameter.
605             If it is \p atomicity::empty_item_counter this function always returns 0.
606
607             The function is not suitable for checking the tree emptiness, use \p empty()
608             member function for this purpose.
609         */
610         size_t size() const
611         {
612             return base_class::size();
613         }
614
615         /// Returns const reference to internal statistics
616         stat const& statistics() const
617         {
618             return base_class::statistics();
619         }
620
621         /// Checks internal consistency (not atomic, not thread-safe)
622         /**
623             The debugging function to check internal consistency of the tree.
624         */
625         bool check_consistency() const
626         {
627             return base_class::check_consistency();
628         }
629
630         /// Checks internal consistency (not atomic, not thread-safe)
631         /**
632             The debugging function to check internal consistency of the tree.
633             The functor \p Func is called if a violation of internal tree structure
634             is found:
635             \code
636             struct functor {
637                 void operator()( size_t nLevel, size_t hLeft, size_t hRight );
638             };
639             \endcode
640             where 
641             - \p nLevel - the level where the violation is found
642             - \p hLeft - the height of left subtree
643             - \p hRight - the height of right subtree
644
645             The functor is called for each violation found.
646         */
647         template <typename Func>
648         bool check_consistency( Func f ) const
649         {
650             return base_class::check_consistency( f );
651         }
652     };
653 }} // namespace cds::container
654
655 #endif // #ifndef CDSLIB_CONTAINER_IMPL_BRONSON_AVLTREE_MAP_RCU_H