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