Merged branch 'master' of https://github.com/Nemo1369/libcds
[libcds.git] / cds / container / impl / ellen_bintree_map.h
1 /*
2     This file is a part of libcds - Concurrent Data Structures library
3
4     (C) Copyright Maxim Khizhinsky (libcds.dev@gmail.com) 2006-2017
5
6     Source code repo: http://github.com/khizmax/libcds/
7     Download: http://sourceforge.net/projects/libcds/files/
8
9     Redistribution and use in source and binary forms, with or without
10     modification, are permitted provided that the following conditions are met:
11
12     * Redistributions of source code must retain the above copyright notice, this
13       list of conditions and the following disclaimer.
14
15     * Redistributions in binary form must reproduce the above copyright notice,
16       this list of conditions and the following disclaimer in the documentation
17       and/or other materials provided with the distribution.
18
19     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20     AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21     IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22     DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23     FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24     DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25     SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26     CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27     OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28     OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31 #ifndef CDSLIB_CONTAINER_IMPL_ELLEN_BINTREE_MAP_H
32 #define CDSLIB_CONTAINER_IMPL_ELLEN_BINTREE_MAP_H
33
34 #include <type_traits>
35 #include <cds/container/details/ellen_bintree_base.h>
36 #include <cds/intrusive/impl/ellen_bintree.h>
37 #include <cds/container/details/guarded_ptr_cast.h>
38
39 namespace cds { namespace container {
40
41     /// Map based on Ellen's et al binary search tree
42     /** @ingroup cds_nonintrusive_map
43         @ingroup cds_nonintrusive_tree
44         @anchor cds_container_EllenBinTreeMap
45
46         Source:
47             - [2010] F.Ellen, P.Fatourou, E.Ruppert, F.van Breugel "Non-blocking Binary Search Tree"
48
49         %EllenBinTreeMap is an unbalanced leaf-oriented binary search tree that implements the <i>map</i>
50         abstract data type. Nodes maintains child pointers but not parent pointers.
51         Every internal node has exactly two children, and all data of type <tt>std::pair<Key const, T></tt>
52         currently in the tree are stored in the leaves. Internal nodes of the tree are used to direct \p find
53         operation along the path to the correct leaf. The keys (of \p Key type) stored in internal nodes
54         may or may not be in the map.
55         Unlike \ref cds_container_EllenBinTreeSet "EllenBinTreeSet" keys are not a part of \p T type.
56         The map can be represented as a set containing <tt>std::pair< Key const, T> </tt> values.
57
58         Due to \p extract_min and \p extract_max member functions the \p %EllenBinTreeMap can act as
59         a <i>priority queue</i>. In this case you should provide unique compound key, for example,
60         the priority value plus some uniformly distributed random value.
61
62         @warning Recall the tree is <b>unbalanced</b>. The complexity of operations is <tt>O(log N)</tt>
63         for uniformly distributed random keys, but in the worst case the complexity is <tt>O(N)</tt>.
64
65         @note In the current implementation we do not use helping technique described in the original paper.
66         In Hazard Pointer schema helping is too complicated and does not give any observable benefits.
67         Instead of helping, when a thread encounters a concurrent operation it just spins waiting for
68         the operation done. Such solution allows greatly simplify implementation of the tree.
69
70         <b>Template arguments</b> :
71         - \p GC - safe memory reclamation (i.e. light-weight garbage collector) type, like \p cds::gc::HP, \p cds::gc::DHP
72         - \p Key - key type. Should be default-constructible
73         - \p T - value type to be stored in tree's leaf nodes.
74         - \p Traits - map traits, default is \p ellen_bintree::traits
75             It is possible to declare option-based tree with \p ellen_bintree::make_map_traits metafunction
76             instead of \p Traits template argument.
77
78         @note Do not include <tt><cds/container/impl/ellen_bintree_map.h></tt> header file directly.
79         There are header file for each GC type:
80         - <tt><cds/container/ellen_bintree_map_hp.h></tt> - for Hazard Pointer GC cds::gc::HP
81         - <tt><cds/container/ellen_bintree_map_dhp.h></tt> - for Dynamic Hazard Pointer GC cds::gc::DHP
82         - <tt><cds/container/ellen_bintree_map_rcu.h></tt> - for RCU GC
83             (see \ref cds_container_EllenBinTreeMap_rcu "RCU-based EllenBinTreeMap")
84     */
85     template <
86         class GC,
87         typename Key,
88         typename T,
89 #ifdef CDS_DOXYGEN_INVOKED
90         class Traits = ellen_bintree::traits
91 #else
92         class Traits
93 #endif
94     >
95     class EllenBinTreeMap
96 #ifdef CDS_DOXYGEN_INVOKED
97         : public cds::intrusive::EllenBinTree< GC, Key, T, Traits >
98 #else
99         : public ellen_bintree::details::make_ellen_bintree_map< GC, Key, T, Traits >::type
100 #endif
101     {
102         //@cond
103         typedef ellen_bintree::details::make_ellen_bintree_map< GC, Key, T, Traits > maker;
104         typedef typename maker::type base_class;
105         //@endcond
106     public:
107         typedef GC      gc;          ///< Garbage collector
108         typedef Key     key_type;    ///< type of a key stored in the map
109         typedef T       mapped_type; ///< type of value stored in the map
110         typedef std::pair< key_type const, mapped_type >    value_type  ;   ///< Key-value pair stored in leaf node of the mp
111         typedef Traits  traits;      ///< Map traits
112
113         static_assert( std::is_default_constructible<key_type>::value, "Key should be default constructible type");
114
115 #   ifdef CDS_DOXYGEN_INVOKED
116         typedef implementation_defined key_comparator; ///< key compare functor based on \p Traits::compare and \p Traits::less
117 #   else
118         typedef typename maker::intrusive_traits::compare   key_comparator;
119 #   endif
120         typedef typename base_class::item_counter           item_counter; ///< Item counting policy
121         typedef typename base_class::memory_model           memory_model; ///< Memory ordering, see \p cds::opt::memory_model
122         typedef typename base_class::node_allocator         node_allocator_type; ///< allocator for maintaining internal node
123         typedef typename base_class::stat                   stat;         ///< internal statistics type
124         typedef typename traits::copy_policy                copy_policy;  ///< key copy policy
125         typedef typename traits::back_off                   back_off;      ///< Back-off strategy
126
127         typedef typename traits::allocator                  allocator_type;   ///< Allocator for leaf nodes
128         typedef typename base_class::node_allocator         node_allocator;   ///< Internal node allocator
129         typedef typename base_class::update_desc_allocator  update_desc_allocator; ///< Update descriptor allocator
130
131     protected:
132         //@cond
133         typedef typename base_class::value_type         leaf_node;
134         typedef typename base_class::internal_node      internal_node;
135         typedef typename base_class::update_desc        update_desc;
136
137         typedef typename maker::cxx_leaf_node_allocator cxx_leaf_node_allocator;
138
139         typedef std::unique_ptr< leaf_node, typename maker::leaf_deallocator >    scoped_node_ptr;
140         //@endcond
141
142     public:
143         /// Guarded pointer
144         typedef typename gc::template guarded_ptr< leaf_node, value_type, details::guarded_ptr_cast_set<leaf_node, value_type> > guarded_ptr;
145
146     public:
147         /// Default constructor
148         EllenBinTreeMap()
149             : base_class()
150         {}
151
152         /// Clears the map
153         ~EllenBinTreeMap()
154         {}
155
156         /// Inserts new node with key and default value
157         /**
158             The function creates a node with \p key and default value, and then inserts the node created into the map.
159
160             Preconditions:
161             - The \ref key_type should be constructible from a value of type \p K.
162                 In trivial case, \p K is equal to \ref key_type.
163             - The \ref mapped_type should be default-constructible.
164
165             Returns \p true if inserting successful, \p false otherwise.
166         */
167         template <typename K>
168         bool insert( K const& key )
169         {
170             return insert_with( key, [](value_type&){} );
171         }
172
173         /// Inserts new node
174         /**
175             The function creates a node with copy of \p val value
176             and then inserts the node created into the map.
177
178             Preconditions:
179             - The \p key_type should be constructible from \p key of type \p K.
180             - The \p value_type should be constructible from \p val of type \p V.
181
182             Returns \p true if \p val is inserted into the map, \p false otherwise.
183         */
184         template <typename K, typename V>
185         bool insert( K const& key, V const& val )
186         {
187             scoped_node_ptr pNode( cxx_leaf_node_allocator().New( key, val ));
188             if ( base_class::insert( *pNode ))
189             {
190                 pNode.release();
191                 return true;
192             }
193             return false;
194         }
195
196         /// Inserts new node and initialize it by a functor
197         /**
198             This function inserts new node with key \p key and if inserting is successful then it calls
199             \p func functor with signature
200             \code
201                 struct functor {
202                     void operator()( value_type& item );
203                 };
204             \endcode
205
206             The argument \p item of user-defined functor \p func is the reference
207             to the map's item inserted:
208                 - <tt>item.first</tt> is a const reference to item's key that cannot be changed.
209                 - <tt>item.second</tt> is a reference to item's value that may be changed.
210
211             The key_type should be constructible from value of type \p K.
212
213             The function allows to split creating of new item into two part:
214             - create item from \p key;
215             - insert new item into the map;
216             - if inserting is successful, initialize the value of item by calling \p func functor
217
218             This can be useful if complete initialization of object of \p value_type is heavyweight and
219             it is preferable that the initialization should be completed only if inserting is successful.
220         */
221         template <typename K, typename Func>
222         bool insert_with( const K& key, Func func )
223         {
224             scoped_node_ptr pNode( cxx_leaf_node_allocator().New( key ));
225             if ( base_class::insert( *pNode, [&func]( leaf_node& item ) { func( item.m_Value ); } )) {
226                 pNode.release();
227                 return true;
228             }
229             return false;
230         }
231
232         /// For key \p key inserts data of type \p value_type created in-place from \p args
233         /**
234             Returns \p true if inserting successful, \p false otherwise.
235         */
236         template <typename K, typename... Args>
237         bool emplace( K&& key, Args&&... args )
238         {
239             scoped_node_ptr pNode( cxx_leaf_node_allocator().MoveNew( key_type( std::forward<K>(key)), mapped_type( std::forward<Args>(args)... )));
240             if ( base_class::insert( *pNode )) {
241                 pNode.release();
242                 return true;
243             }
244             return false;
245         }
246
247         /// Updates the node
248         /**
249             The operation performs inserting or changing data with lock-free manner.
250
251             If the item \p val is not found in the map, then \p val is inserted iff \p bAllowInsert is \p true.
252             Otherwise, the functor \p func is called with item found.
253             The functor \p func signature is:
254             \code
255                 struct my_functor {
256                     void operator()( bool bNew, value_type& item );
257                 };
258             \endcode
259
260             with arguments:
261             - \p bNew - \p true if the item has been inserted, \p false otherwise
262             - \p item - item of the map
263
264             The functor may change any fields of the \p item.second that is \ref mapped_type;
265             however, \p func must guarantee that during changing no any other modifications
266             could be made on this item by concurrent threads.
267
268             Returns std::pair<bool, bool> where \p first is \p true if operation is successful,
269             i.e. the node has been inserted or updated,
270             \p second is \p true if new item has been added or \p false if the item with \p key
271             already exists.
272
273             @warning See \ref cds_intrusive_item_creating "insert item troubleshooting"
274         */
275         template <typename K, typename Func>
276         std::pair<bool, bool> update( K const& key, Func func, bool bAllowInsert = true )
277         {
278             scoped_node_ptr pNode( cxx_leaf_node_allocator().New( key ));
279             std::pair<bool, bool> res = base_class::update( *pNode,
280                 [&func](bool bNew, leaf_node& item, leaf_node const& ){ func( bNew, item.m_Value ); },
281                 bAllowInsert
282             );
283             if ( res.first && res.second )
284                 pNode.release();
285             return res;
286         }
287         //@cond
288         template <typename K, typename Func>
289         CDS_DEPRECATED("ensure() is deprecated, use update()")
290         std::pair<bool, bool> ensure( K const& key, Func func )
291         {
292             return update( key, func, true );
293         }
294         //@endcond
295
296         /// Delete \p key from the map
297         /**\anchor cds_nonintrusive_EllenBinTreeMap_erase_val
298
299             Return \p true if \p key is found and deleted, \p false otherwise
300         */
301         template <typename K>
302         bool erase( K const& key )
303         {
304             return base_class::erase(key);
305         }
306
307         /// Deletes the item from the map using \p pred predicate for searching
308         /**
309             The function is an analog of \ref cds_nonintrusive_EllenBinTreeMap_erase_val "erase(K const&)"
310             but \p pred is used for key comparing.
311             \p Less functor has the interface like \p std::less.
312             \p Less must imply the same element order as the comparator used for building the map.
313         */
314         template <typename K, typename Less>
315         bool erase_with( K const& key, Less pred )
316         {
317             CDS_UNUSED( pred );
318             return base_class::erase_with( key, cds::details::predicate_wrapper< leaf_node, Less, typename maker::key_accessor >());
319         }
320
321         /// Delete \p key from the map
322         /** \anchor cds_nonintrusive_EllenBinTreeMap_erase_func
323
324             The function searches an item with key \p key, calls \p f functor
325             and deletes the item. If \p key is not found, the functor is not called.
326
327             The functor \p Func interface:
328             \code
329             struct extractor {
330                 void operator()(value_type& item) { ... }
331             };
332             \endcode
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]( leaf_node& node) { f( node.m_Value ); } );
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_EllenBinTreeMap_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             CDS_UNUSED( pred );
353             return base_class::erase_with( key, cds::details::predicate_wrapper< leaf_node, Less, typename maker::key_accessor >(),
354                 [&f]( leaf_node& node) { f( node.m_Value ); } );
355         }
356
357         /// Extracts an item with minimal key from the map
358         /**
359             If the map is not empty, the function returns an guarded pointer to minimum value.
360             If the map is empty, the function returns an empty \p guarded_ptr.
361
362             @note Due the concurrent nature of the map, the function extracts <i>nearly</i> minimum key.
363             It means that the function gets leftmost leaf of the tree and tries to unlink it.
364             During unlinking, a concurrent thread may insert an item with key less than leftmost item's key.
365             So, the function returns the item with minimum key at the moment of tree traversing.
366
367             The guarded pointer prevents deallocation of returned item,
368             see \p cds::gc::guarded_ptr for explanation.
369             @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
370         */
371         guarded_ptr extract_min()
372         {
373             return guarded_ptr( base_class::extract_min_());
374         }
375
376         /// Extracts an item with maximal key from the map
377         /**
378             If the map is not empty, the function returns a guarded pointer to maximal value.
379             If the map is empty, the function returns an empty \p guarded_ptr.
380
381             @note Due the concurrent nature of the map, the function extracts <i>nearly</i> maximal key.
382             It means that the function gets rightmost leaf of the tree and tries to unlink it.
383             During unlinking, a concurrent thread may insert an item with key great than leftmost item's key.
384             So, the function returns the item with maximum key at the moment of tree traversing.
385
386             The guarded pointer prevents deallocation of returned item,
387             see \p cds::gc::guarded_ptr for explanation.
388             @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
389         */
390         guarded_ptr extract_max()
391         {
392             return guarded_ptr( base_class::extract_max_());
393         }
394
395         /// Extracts an item from the tree
396         /** \anchor cds_nonintrusive_EllenBinTreeMap_extract
397             The function searches an item with key equal to \p key in the tree,
398             unlinks it, and returns a guarded pointer to an item found.
399             If the item  is not found the function returns an empty \p guarded_ptr.
400
401             The guarded pointer prevents deallocation of returned item,
402             see \p cds::gc::guarded_ptr for explanation.
403             @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
404         */
405         template <typename Q>
406         guarded_ptr extract( Q const& key )
407         {
408             return guarded_ptr( base_class::extract_( key ));
409         }
410
411         /// Extracts an item from the map using \p pred for searching
412         /**
413             The function is an analog of \ref cds_nonintrusive_EllenBinTreeMap_extract "extract(Q const&)"
414             but \p pred is used for key compare.
415             \p Less has the interface like \p std::less.
416             \p pred must imply the same element order as the comparator used for building the map.
417         */
418         template <typename Q, typename Less>
419         guarded_ptr extract_with( Q const& key, Less pred )
420         {
421             CDS_UNUSED( pred );
422             return guarded_ptr( base_class::extract_with_( key,
423                 cds::details::predicate_wrapper< leaf_node, Less, typename maker::key_accessor >()));
424         }
425
426         /// Find the key \p key
427         /** \anchor cds_nonintrusive_EllenBinTreeMap_find_cfunc
428
429             The function searches the item with key equal to \p key and calls the functor \p f for item found.
430             The interface of \p Func functor is:
431             \code
432             struct functor {
433                 void operator()( value_type& item );
434             };
435             \endcode
436             where \p item is the item found.
437
438             The functor may change \p item.second.
439
440             The function returns \p true if \p key is found, \p false otherwise.
441         */
442         template <typename K, typename Func>
443         bool find( K const& key, Func f )
444         {
445             return base_class::find( key, [&f](leaf_node& item, K const& ) { f( item.m_Value );});
446         }
447
448         /// Finds the key \p val using \p pred predicate for searching
449         /**
450             The function is an analog of \ref cds_nonintrusive_EllenBinTreeMap_find_cfunc "find(K const&, Func)"
451             but \p pred is used for key comparing.
452             \p Less functor has the interface like \p std::less.
453             \p Less must imply the same element order as the comparator used for building the map.
454         */
455         template <typename K, typename Less, typename Func>
456         bool find_with( K const& key, Less pred, Func f )
457         {
458             CDS_UNUSED( pred );
459             return base_class::find_with( key, cds::details::predicate_wrapper< leaf_node, Less, typename maker::key_accessor >(),
460                 [&f](leaf_node& item, K const& ) { f( item.m_Value );});
461         }
462
463         /// Checks whether the map contains \p key
464         /**
465             The function searches the item with key equal to \p key
466             and returns \p true if it is found, and \p false otherwise.
467         */
468         template <typename K>
469         bool contains( K const& key )
470         {
471             return base_class::contains( key );
472         }
473         //@cond
474         template <typename K>
475         CDS_DEPRECATED("deprecated, use contains()")
476         bool find( K const& key )
477         {
478             return contains( key );
479         }
480         //@endcond
481
482         /// Checks whether the map contains \p key using \p pred predicate for searching
483         /**
484             The function is similar to <tt>contains( key )</tt> but \p pred is used for key comparing.
485             \p Less functor has the interface like \p std::less.
486             \p Less must imply the same element order as the comparator used for building the set.
487         */
488         template <typename K, typename Less>
489         bool contains( K const& key, Less pred )
490         {
491             CDS_UNUSED( pred );
492             return base_class::contains( key, cds::details::predicate_wrapper< leaf_node, Less, typename maker::key_accessor >());
493         }
494         //@cond
495         template <typename K, typename Less>
496         CDS_DEPRECATED("deprecated, use contains()")
497         bool find_with( K const& key, Less pred )
498         {
499             return contains( key, pred );
500         }
501         //@endcond
502
503         /// Finds \p key and returns the item found
504         /** @anchor cds_nonintrusive_EllenBinTreeMap_get
505             The function searches the item with key equal to \p key and returns the item found as a guarded pointer.
506             If \p key is not foudn the function returns an empty \p guarded_ptr.
507
508             The guarded pointer prevents deallocation of returned item,
509             see \p cds::gc::guarded_ptr for explanation.
510             @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
511         */
512         template <typename Q>
513         guarded_ptr get( Q const& key )
514         {
515             return guarded_ptr( base_class::get_( key ));
516         }
517
518         /// Finds \p key with predicate \p pred and returns the item found
519         /**
520             The function is an analog of \ref cds_nonintrusive_EllenBinTreeMap_get "get(Q const&)"
521             but \p pred is used for key comparing.
522             \p Less functor has the interface like \p std::less.
523             \p pred must imply the same element order as the comparator used for building the map.
524         */
525         template <typename Q, typename Less>
526         guarded_ptr get_with( Q const& key, Less pred )
527         {
528             CDS_UNUSED( pred );
529             return guarded_ptr( base_class::get_with_( key,
530                 cds::details::predicate_wrapper< leaf_node, Less, typename maker::key_accessor >()));
531         }
532
533         /// Clears the map (not atomic)
534         void clear()
535         {
536             base_class::clear();
537         }
538
539         /// Checks if the map is empty
540         /**
541             Emptiness is checked by item counting: if item count is zero then the map is empty.
542         */
543         bool empty() const
544         {
545             return base_class::empty();
546         }
547
548         /// Returns item count in the set
549         /**
550             Only leaf nodes containing user data are counted.
551
552             The value returned depends on item counter type provided by \p Traits template parameter.
553             If it is \p atomicity::empty_item_counter this function always returns 0.
554
555             The function is not suitable for checking the tree emptiness, use \p empty()
556             member function for this purpose.
557         */
558         size_t size() const
559         {
560             return base_class::size();
561         }
562
563         /// Returns const reference to internal statistics
564         stat const& statistics() const
565         {
566             return base_class::statistics();
567         }
568
569         /// Checks internal consistency (not atomic, not thread-safe)
570         /**
571             The debugging function to check internal consistency of the tree.
572         */
573         bool check_consistency() const
574         {
575             return base_class::check_consistency();
576         }
577
578     };
579 }} // namespace cds::container
580
581 #endif //#ifndef CDSLIB_CONTAINER_IMPL_ELLEN_BINTREE_MAP_H