EllenBinTreeMap, EllenBinTreeSet:
[libcds.git] / cds / container / impl / ellen_bintree_map.h
1 //$$CDS-header$$
2
3 #ifndef CDSLIB_CONTAINER_IMPL_ELLEN_BINTREE_MAP_H
4 #define CDSLIB_CONTAINER_IMPL_ELLEN_BINTREE_MAP_H
5
6 #include <type_traits>
7 #include <cds/container/details/ellen_bintree_base.h>
8 #include <cds/intrusive/impl/ellen_bintree.h>
9 #include <cds/container/details/guarded_ptr_cast.h>
10
11 namespace cds { namespace container {
12
13     /// Map based on Ellen's et al binary search tree
14     /** @ingroup cds_nonintrusive_map
15         @ingroup cds_nonintrusive_tree
16         @anchor cds_container_EllenBinTreeMap
17
18         Source:
19             - [2010] F.Ellen, P.Fatourou, E.Ruppert, F.van Breugel "Non-blocking Binary Search Tree"
20
21         %EllenBinTreeMap is an unbalanced leaf-oriented binary search tree that implements the <i>map</i>
22         abstract data type. Nodes maintains child pointers but not parent pointers.
23         Every internal node has exactly two children, and all data of type <tt>std::pair<Key const, T></tt>
24         currently in the tree are stored in the leaves. Internal nodes of the tree are used to direct \p find
25         operation along the path to the correct leaf. The keys (of \p Key type) stored in internal nodes
26         may or may not be in the map.
27         Unlike \ref cds_container_EllenBinTreeSet "EllenBinTreeSet" keys are not a part of \p T type.
28         The map can be represented as a set containing <tt>std::pair< Key const, T> </tt> values.
29
30         Due to \p extract_min and \p extract_max member functions the \p %EllenBinTreeMap can act as
31         a <i>priority queue</i>. In this case you should provide unique compound key, for example,
32         the priority value plus some uniformly distributed random value.
33
34         @warning Recall the tree is <b>unbalanced</b>. The complexity of operations is <tt>O(log N)</tt>
35         for uniformly distributed random keys, but in worst case the complexity is <tt>O(N)</tt>.
36
37         @note In the current implementation we do not use helping technique described in the original paper.
38         In Hazard Pointer schema helping is too complicated and does not give any observable benefits.
39         Instead of helping, when a thread encounters a concurrent operation it just spins waiting for
40         the operation done. Such solution allows greatly simplify implementation of the tree.
41
42         <b>Template arguments</b> :
43         - \p GC - safe memory reclamation (i.e. light-weight garbage collector) type, like \p cds::gc::HP, \p cds::gc::DHP
44         - \p Key - key type
45         - \p T - value type to be stored in tree's leaf nodes.
46         - \p Traits - map traits, default is \p ellen_bintree::traits
47             It is possible to declare option-based tree with \p ellen_bintree::make_map_traits metafunction
48             instead of \p Traits template argument.
49
50         @note Do not include <tt><cds/container/impl/ellen_bintree_map.h></tt> header file directly.
51         There are header file for each GC type:
52         - <tt><cds/container/ellen_bintree_map_hp.h></tt> - for Hazard Pointer GC cds::gc::HP
53         - <tt><cds/container/ellen_bintree_map_dhp.h></tt> - for Dynamic Hazard Pointer GC cds::gc::DHP
54         - <tt><cds/container/ellen_bintree_map_rcu.h></tt> - for RCU GC
55             (see \ref cds_container_EllenBinTreeMap_rcu "RCU-based EllenBinTreeMap")
56     */
57     template <
58         class GC,
59         typename Key,
60         typename T,
61 #ifdef CDS_DOXYGEN_INVOKED
62         class Traits = ellen_bintree::traits
63 #else
64         class Traits
65 #endif
66     >
67     class EllenBinTreeMap
68 #ifdef CDS_DOXYGEN_INVOKED
69         : public cds::intrusive::EllenBinTree< GC, Key, T, Traits >
70 #else
71         : public ellen_bintree::details::make_ellen_bintree_map< GC, Key, T, Traits >::type
72 #endif
73     {
74         //@cond
75         typedef ellen_bintree::details::make_ellen_bintree_map< GC, Key, T, Traits > maker;
76         typedef typename maker::type base_class;
77         //@endcond
78     public:
79         typedef GC      gc;          ///< Garbage collector
80         typedef Key     key_type;    ///< type of a key stored in the map
81         typedef T       mapped_type; ///< type of value stored in the map
82         typedef std::pair< key_type const, mapped_type >    value_type  ;   ///< Key-value pair stored in leaf node of the mp
83         typedef Traits  traits;      ///< Map traits
84
85 #   ifdef CDS_DOXYGEN_INVOKED
86         typedef implementation_defined key_comparator; ///< key compare functor based on \p Traits::compare and \p Traits::less
87 #   else
88         typedef typename maker::intrusive_traits::compare   key_comparator;
89 #   endif
90         typedef typename base_class::item_counter           item_counter; ///< Item counting policy
91         typedef typename base_class::memory_model           memory_model; ///< Memory ordering, see \p cds::opt::memory_model
92         typedef typename base_class::node_allocator         node_allocator_type; ///< allocator for maintaining internal node
93         typedef typename base_class::stat                   stat;         ///< internal statistics type
94         typedef typename traits::copy_policy                copy_policy;  ///< key copy policy
95         typedef typename traits::back_off                   back_off;      ///< Back-off strategy
96
97         typedef typename traits::allocator                  allocator_type;   ///< Allocator for leaf nodes
98         typedef typename base_class::node_allocator         node_allocator;   ///< Internal node allocator
99         typedef typename base_class::update_desc_allocator  update_desc_allocator; ///< Update descriptor allocator
100
101         //@cond
102         typedef cds::container::ellen_bintree::implementation_tag implementation_tag;
103         //@endcond
104
105     protected:
106         //@cond
107         typedef typename base_class::value_type         leaf_node;
108         typedef typename base_class::internal_node      internal_node;
109         typedef typename base_class::update_desc        update_desc;
110
111         typedef typename maker::cxx_leaf_node_allocator cxx_leaf_node_allocator;
112
113         typedef std::unique_ptr< leaf_node, typename maker::leaf_deallocator >    scoped_node_ptr;
114         //@endcond
115
116     public:
117         /// Guarded pointer
118         typedef typename gc::template guarded_ptr< leaf_node, value_type, details::guarded_ptr_cast_set<leaf_node, value_type> > guarded_ptr;
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 \ref key_type should be constructible from a value of type \p K.
136                 In trivial case, \p K is equal to \ref key_type.
137             - The \ref mapped_type should be default-constructible.
138
139             Returns \p true if inserting successful, \p false otherwise.
140         */
141         template <typename K>
142         bool insert( K const& key )
143         {
144             return insert_with( key, [](value_type&){} );
145         }
146
147         /// Inserts new node
148         /**
149             The function creates a node with copy of \p val value
150             and then inserts the node created into the map.
151
152             Preconditions:
153             - The \p key_type should be constructible from \p key of type \p K.
154             - The \p value_type should be constructible from \p val of type \p V.
155
156             Returns \p true if \p val is inserted into the map, \p false otherwise.
157         */
158         template <typename K, typename V>
159         bool insert( K const& key, V const& val )
160         {
161             scoped_node_ptr pNode( cxx_leaf_node_allocator().New( key, val ));
162             if ( base_class::insert( *pNode ))
163             {
164                 pNode.release();
165                 return true;
166             }
167             return false;
168         }
169
170         /// Inserts new node and initialize it by a functor
171         /**
172             This function inserts new node with key \p key and if inserting is successful then it calls
173             \p func functor with signature
174             \code
175                 struct functor {
176                     void operator()( value_type& item );
177                 };
178             \endcode
179
180             The argument \p item of user-defined functor \p func is the reference
181             to the map's item inserted:
182                 - <tt>item.first</tt> is a const reference to item's key that cannot be changed.
183                 - <tt>item.second</tt> is a reference to item's value that may be changed.
184
185             The key_type should be constructible from value of type \p K.
186
187             The function allows to split creating of new item into two part:
188             - create item from \p key;
189             - insert new item into the map;
190             - if inserting is successful, initialize the value of item by calling \p func functor
191
192             This can be useful if complete initialization of object of \p value_type is heavyweight and
193             it is preferable that the initialization should be completed only if inserting is successful.
194         */
195         template <typename K, typename Func>
196         bool insert_with( 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         template <typename K, typename... Args>
211         bool emplace( K&& key, Args&&... args )
212         {
213             scoped_node_ptr pNode( cxx_leaf_node_allocator().New( std::forward<K>(key), std::forward<Args>(args)... ));
214             if ( base_class::insert( *pNode )) {
215                 pNode.release();
216                 return true;
217             }
218             return false;
219         }
220
221         /// Updates the node
222         /**
223             The operation performs inserting or changing data with lock-free manner.
224
225             If the item \p val is not found in the map, then \p val is inserted iff \p bAllowInsert is \p true.
226             Otherwise, the functor \p func is called with item found.
227             The functor \p func signature is:
228             \code
229                 struct my_functor {
230                     void operator()( bool bNew, value_type& item );
231                 };
232             \endcode
233
234             with arguments:
235             - \p bNew - \p true if the item has been inserted, \p false otherwise
236             - \p item - item of the map
237
238             The functor may change any fields of the \p item.second that is \ref mapped_type;
239             however, \p func must guarantee that during changing no any other modifications
240             could be made on this item by concurrent threads.
241
242             Returns std::pair<bool, bool> where \p first is \p true if operation is successfull,
243             i.e. the node has been inserted or updated,
244             \p second is \p true if new item has been added or \p false if the item with \p key
245             already exists.
246
247             @warning See \ref cds_intrusive_item_creating "insert item troubleshooting"
248         */
249         template <typename K, typename Func>
250         std::pair<bool, bool> update( K const& key, Func func, bool bAllowInsert = true )
251         {
252             scoped_node_ptr pNode( cxx_leaf_node_allocator().New( key ));
253             std::pair<bool, bool> res = base_class::update( *pNode,
254                 [&func](bool bNew, leaf_node& item, leaf_node const& ){ func( bNew, item.m_Value ); },
255                 bAllowInsert
256             );
257             if ( res.first && res.second )
258                 pNode.release();
259             return res;
260         }
261         //@cond
262         // Deprecated, use update()
263         template <typename K, typename Func>
264         std::pair<bool, bool> ensure( K const& key, Func func )
265         {
266             return update( key, func, true );
267         }
268         //@endcond
269
270         /// Delete \p key from the map
271         /**\anchor cds_nonintrusive_EllenBinTreeMap_erase_val
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_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             CDS_UNUSED( pred );
292             return base_class::erase_with( key, cds::details::predicate_wrapper< leaf_node, Less, typename maker::key_accessor >());
293         }
294
295         /// Delete \p key from the map
296         /** \anchor cds_nonintrusive_EllenBinTreeMap_erase_func
297
298             The function searches an item with key \p key, calls \p f functor
299             and deletes the item. If \p key is not found, the functor is not called.
300
301             The functor \p Func interface:
302             \code
303             struct extractor {
304                 void operator()(value_type& item) { ... }
305             };
306             \endcode
307
308             Return \p true if key is found and deleted, \p false otherwise
309         */
310         template <typename K, typename Func>
311         bool erase( K const& key, Func f )
312         {
313             return base_class::erase( key, [&f]( leaf_node& node) { f( node.m_Value ); } );
314         }
315
316         /// Deletes the item from the map using \p pred predicate for searching
317         /**
318             The function is an analog of \ref cds_nonintrusive_EllenBinTreeMap_erase_func "erase(K const&, Func)"
319             but \p pred is used for key comparing.
320             \p Less functor has the interface like \p std::less.
321             \p Less must imply the same element order as the comparator used for building the map.
322         */
323         template <typename K, typename Less, typename Func>
324         bool erase_with( K const& key, Less pred, Func f )
325         {
326             CDS_UNUSED( pred );
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 an guarded pointer to minimum value.
334             If the map is empty, the function returns an empty \p guarded_ptr.
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             The guarded pointer prevents deallocation of returned item,
342             see \p cds::gc::guarded_ptr for explanation.
343             @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
344         */
345         guarded_ptr extract_min()
346         {
347             guarded_ptr gp;
348             base_class::extract_min_( gp.guard() );
349             return gp;
350         }
351
352         /// Extracts an item with maximal key from the map
353         /**
354             If the map is not empty, the function returns a guarded pointer to maximal value.
355             If the map is empty, the function returns an empty \p guarded_ptr.
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             The guarded pointer prevents deallocation of returned item,
363             see \p cds::gc::guarded_ptr for explanation.
364             @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
365         */
366         guarded_ptr extract_max()
367         {
368             guarded_ptr gp;
369             base_class::extract_max_( gp.guard() );
370             return gp;
371         }
372
373         /// Extracts an item from the tree
374         /** \anchor cds_nonintrusive_EllenBinTreeMap_extract
375             The function searches an item with key equal to \p key in the tree,
376             unlinks it, and returns a guarded pointer to an item found.
377             If the item  is not found the function returns an empty \p guarded_ptr.
378
379             The guarded pointer prevents deallocation of returned item,
380             see \p cds::gc::guarded_ptr for explanation.
381             @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
382         */
383         template <typename Q>
384         guarded_ptr extract( Q const& key )
385         {
386             guarded_ptr gp;
387             base_class::extract_( gp.guard(), key );
388             return gp;
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_extract "extract(Q const&)"
394             but \p pred is used for key compare.
395             \p Less has the interface like \p std::less.
396             \p pred must imply the same element order as the comparator used for building the map.
397         */
398         template <typename Q, typename Less>
399         guarded_ptr extract_with( Q const& key, Less pred )
400         {
401             CDS_UNUSED( pred );
402             guarded_ptr gp;
403             base_class::extract_with_( gp.guard(), key,
404                 cds::details::predicate_wrapper< leaf_node, Less, typename maker::key_accessor >());
405             return gp;
406         }
407
408         /// Find the key \p key
409         /** \anchor cds_nonintrusive_EllenBinTreeMap_find_cfunc
410
411             The function searches the item with key equal to \p key and calls the functor \p f for item found.
412             The interface of \p Func functor is:
413             \code
414             struct functor {
415                 void operator()( value_type& item );
416             };
417             \endcode
418             where \p item is the item found.
419
420             The functor may change \p item.second.
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_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             CDS_UNUSED( pred );
441             return base_class::find_with( key, cds::details::predicate_wrapper< leaf_node, Less, typename maker::key_accessor >(),
442                 [&f](leaf_node& item, K const& ) { f( item.m_Value );});
443         }
444
445         /// Checks whether the map contains \p key
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         template <typename K>
451         bool contains( K const& key )
452         {
453             return base_class::contains( key );
454         }
455         //@cond
456         // Deprecated, use contains()
457         template <typename K>
458         bool find( K const& key )
459         {
460             return contains( key );
461         }
462         //@endcond
463
464         /// Checks whether the map contains \p key using \p pred predicate for searching
465         /**
466             The function is similar to <tt>contains( key )</tt> but \p pred is used for key comparing.
467             \p Less functor has the interface like \p std::less.
468             \p Less must imply the same element order as the comparator used for building the set.
469         */
470         template <typename K, typename Less>
471         bool contains( K const& key, Less pred )
472         {
473             CDS_UNUSED( pred );
474             return base_class::contains( key, cds::details::predicate_wrapper< leaf_node, Less, typename maker::key_accessor >() );
475         }
476         //@cond
477         // Deprecated, use contains()
478         template <typename K, typename Less>
479         bool find_with( K const& key, Less pred )
480         {
481             return contains( key, pred );
482         }
483         //@endcond
484
485         /// Finds \p key and returns the item found
486         /** @anchor cds_nonintrusive_EllenBinTreeMap_get
487             The function searches the item with key equal to \p key and returns the item found as a guarded pointer.
488             If \p key is not foudn the function returns an empty \p guarded_ptr.
489
490             The guarded pointer prevents deallocation of returned item,
491             see \p cds::gc::guarded_ptr for explanation.
492             @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
493         */
494         template <typename Q>
495         guarded_ptr get( Q const& key )
496         {
497             guarded_ptr gp;
498             base_class::get_( gp.guard(), key );
499             return gp;
500         }
501
502         /// Finds \p key with predicate \p pred and returns the item found
503         /**
504             The function is an analog of \ref cds_nonintrusive_EllenBinTreeMap_get "get(Q const&)"
505             but \p pred is used for key comparing.
506             \p Less functor has the interface like \p std::less.
507             \p pred must imply the same element order as the comparator used for building the map.
508         */
509         template <typename Q, typename Less>
510         guarded_ptr get_with( Q const& key, Less pred )
511         {
512             CDS_UNUSED( pred );
513             guarded_ptr gp;
514             base_class::get_with_( gp.guard(), key,
515                 cds::details::predicate_wrapper< leaf_node, Less, typename maker::key_accessor >() );
516             return gp;
517         }
518
519         /// Clears the map (not atomic)
520         void clear()
521         {
522             base_class::clear();
523         }
524
525         /// Checks if the map is empty
526         /**
527             Emptiness is checked by item counting: if item count is zero then the map is empty.
528         */
529         bool empty() const
530         {
531             return base_class::empty();
532         }
533
534         /// Returns item count in the set
535         /**
536             Only leaf nodes containing user data are counted.
537
538             The value returned depends on item counter type provided by \p Traits template parameter.
539             If it is \p atomicity::empty_item_counter this function always returns 0.
540
541             The function is not suitable for checking the tree emptiness, use \p empty()
542             member function for this purpose.
543         */
544         size_t size() const
545         {
546             return base_class::size();
547         }
548
549         /// Returns const reference to internal statistics
550         stat const& statistics() const
551         {
552             return base_class::statistics();
553         }
554
555         /// Checks internal consistency (not atomic, not thread-safe)
556         /**
557             The debugging function to check internal consistency of the tree.
558         */
559         bool check_consistency() const
560         {
561             return base_class::check_consistency();
562         }
563
564     };
565 }} // namespace cds::container
566
567 #endif //#ifndef CDSLIB_CONTAINER_IMPL_ELLEN_BINTREE_MAP_H