Fixed iterator issues in set/map
[libcds.git] / cds / container / split_list_map.h
1 //$$CDS-header$$
2
3 #ifndef __CDS_CONTAINER_SPLIT_LIST_MAP_H
4 #define __CDS_CONTAINER_SPLIT_LIST_MAP_H
5
6 #include <cds/container/split_list_set.h>
7 #include <cds/details/binary_functor_wrapper.h>
8
9 namespace cds { namespace container {
10
11     /// Split-ordered list map
12     /** @ingroup cds_nonintrusive_map
13         \anchor cds_nonintrusive_SplitListMap_hp
14
15         Hash table implementation based on split-ordered list algorithm discovered by Ori Shalev and Nir Shavit, see
16         - [2003] Ori Shalev, Nir Shavit "Split-Ordered Lists - Lock-free Resizable Hash Tables"
17         - [2008] Nir Shavit "The Art of Multiprocessor Programming"
18
19         See intrusive::SplitListSet for a brief description of the split-list algorithm.
20
21         Template parameters:
22         - \p GC - Garbage collector used
23         - \p Key - key type of an item stored in the map. It should be copy-constructible
24         - \p Value - value type stored in the map
25         - \p Traits - map traits, default is \p split_list::traits. Instead of declaring \p %split_list::traits -based
26             struct you may apply option-based notation with \p split_list::make_traits metafunction.
27
28         There are the specializations:
29         - for \ref cds_urcu_desc "RCU" - declared in <tt>cd/container/split_list_map_rcu.h</tt>,
30             see \ref cds_nonintrusive_SplitListMap_rcu "SplitListMap<RCU>".
31         - for \ref cds::gc::nogc declared in <tt>cds/container/split_list_map_nogc.h</tt>,
32             see \ref cds_nonintrusive_SplitListMap_nogc "SplitListMap<gc::nogc>".
33
34         \par Usage
35
36         You should decide what garbage collector you want, and what ordered list you want to use. Split-ordered list
37         is original data structure based on an ordered list. Suppose, you want construct split-list map based on \p gc::HP GC
38         and \p MichaelList as ordered list implementation. Your map should map \p int key to \p std::string value.
39         So, you beginning your program with following include:
40         \code
41         #include <cds/container/michael_list_hp.h>
42         #include <cds/container/split_list_map.h>
43
44         namespace cc = cds::container;
45         \endcode
46         The inclusion order is important: first, include file for ordered-list implementation (for this example, <tt>cds/container/michael_list_hp.h</tt>),
47         then the header for split-list map <tt>cds/container/split_list_map.h</tt>.
48
49         Now, you should declare traits for split-list map. The main parts of traits are a hash functor and a comparing functor for the ordered list.
50         We use <tt>std::hash<int></tt> as hash functor and <tt>std::less<int></tt> predicate as comparing functor.
51
52         The second attention: instead of using \p %MichaelList in \p %SplitListMap traits we use a tag \p cds::contaner::michael_list_tag for the Michael's list.
53         The split-list requires significant support from underlying ordered list class and it is not good idea to dive you
54         into deep implementation details of split-list and ordered list interrelations. The tag paradigm simplifies split-list interface.
55
56         \code
57         // SplitListMap traits
58         struct foo_set_traits: public cc::split_list::traits
59         {
60             typedef cc::michael_list_tag   ordered_list    ;   // what type of ordered list we want to use
61             typedef std::hash<int>         hash            ;   // hash functor for the key stored in split-list map
62
63             // Type traits for our MichaelList class
64             struct ordered_list_traits: public cc::michael_list::traits
65             {
66             typedef std::less<int> less   ;   // use our std::less predicate as comparator to order list nodes
67             };
68         };
69         \endcode
70
71         Now you are ready to declare our map class based on \p %SplitListMap:
72         \code
73         typedef cc::SplitListMap< cds::gc::PTB, int, std::string, foo_set_traits > int_string_map;
74         \endcode
75
76         You may use the modern option-based declaration instead of classic type-traits-based one:
77         \code
78         typedef cc:SplitListMap<
79             cs::gc::PTB             // GC used
80             ,int                    // key type
81             ,std::string            // value type
82             ,cc::split_list::make_traits<      // metafunction to build split-list traits
83                 cc::split_list::ordered_list<cc::michael_list_tag>     // tag for underlying ordered list implementation
84                 ,cc::opt::hash< std::hash<int> >        // hash functor
85                 ,cc::split_list::ordered_list_traits<    // ordered list traits desired
86                     cc::michael_list::make_traits<    // metafunction to build lazy list traits
87                         cc::opt::less< std::less<int> >         // less-based compare functor
88                     >::type
89                 >
90             >::type
91         >  int_string_map;
92         \endcode
93         In case of option-based declaration with \p split_list::make_traits metafunction the struct \p foo_set_traits is not required.
94
95         Now, the map of type \p int_string_map is ready to use in your program.
96
97         Note that in this example we show only mandatory \p traits parts, optional ones is the default and they are inherited
98         from \p container::split_list::traits. There are many other options for deep tuning of the split-list and
99         ordered-list containers.
100     */
101     template <
102         class GC,
103         typename Key,
104         typename Value,
105 #ifdef CDS_DOXYGEN_INVOKED
106         class Traits = split_list::traits
107 #else
108         class Traits
109 #endif
110     >
111     class SplitListMap:
112         protected container::SplitListSet<
113             GC,
114             std::pair<Key const, Value>,
115             split_list::details::wrap_map_traits<Key, Value, Traits>
116         >
117     {
118         //@cond
119         typedef container::SplitListSet<
120             GC,
121             std::pair<Key const, Value>,
122             split_list::details::wrap_map_traits<Key, Value, Traits>
123         >  base_class;
124         //@endcond
125
126     public:
127         typedef GC     gc;          ///< Garbage collector
128         typedef Key    key_type;    ///< key type
129         typedef Value  mapped_type; ///< type of value to be stored in the map
130         typedef Traits options;     ///< Map traits
131
132         typedef std::pair<key_type const, mapped_type>  value_type  ;   ///< key-value pair type
133         typedef typename base_class::ordered_list       ordered_list;   ///< Underlying ordered list class
134         typedef typename base_class::key_comparator     key_comparator; ///< key compare functor
135
136         typedef typename base_class::hash           hash;         ///< Hash functor for \ref key_type
137         typedef typename base_class::item_counter   item_counter; ///< Item counter type
138         typedef typename base_class::stat           stat;         ///< Internal statistics
139
140     protected:
141         //@cond
142         typedef typename base_class::maker::traits::key_accessor key_accessor;
143         typedef typename base_class::node_type node_type;
144         //@endcond
145
146     public:
147         /// Guarded pointer
148         typedef cds::gc::guarded_ptr< gc, node_type, value_type, details::guarded_ptr_cast_set<node_type, value_type> > guarded_ptr;
149
150     public:
151         /// Forward iterator (see \p SplitListSet::iterator)
152         /**
153             Remember, the iterator <tt>operator -> </tt> and <tt>operator *</tt> returns \ref value_type pointer and reference.
154             To access item key and value use <tt>it->first</tt> and <tt>it->second</tt> respectively.
155         */
156         typedef typename base_class::iterator iterator;
157
158         /// Const forward iterator (see SplitListSet::const_iterator)
159         typedef typename base_class::const_iterator const_iterator;
160
161         /// Returns a forward iterator addressing the first element in a map
162         /**
163             For empty map \code begin() == end() \endcode
164         */
165         iterator begin()
166         {
167             return base_class::begin();
168         }
169
170         /// Returns an iterator that addresses the location succeeding the last element in a map
171         /**
172             Do not use the value returned by <tt>end</tt> function to access any item.
173             The returned value can be used only to control reaching the end of the map.
174             For empty map \code begin() == end() \endcode
175         */
176         iterator end()
177         {
178             return base_class::end();
179         }
180
181         /// Returns a forward const iterator addressing the first element in a map
182         //@{
183         const_iterator begin() const
184         {
185             return base_class::begin();
186         }
187         const_iterator cbegin() const
188         {
189             return base_class::cbegin();
190         }
191         //@}
192
193         /// Returns an const iterator that addresses the location succeeding the last element in a map
194         //@{
195         const_iterator end() const
196         {
197             return base_class::end();
198         }
199         const_iterator cend() const
200         {
201             return base_class::cend();
202         }
203         //@}
204
205     public:
206         /// Initializes split-ordered map of default capacity
207         /**
208             The default capacity is defined in bucket table constructor.
209             See \p intrusive::split_list::expandable_bucket_table, \p intrusive::split_list::static_bucket_table
210             which selects by \p intrusive::split_list::traits::dynamic_bucket_table.
211         */
212         SplitListMap()
213             : base_class()
214         {}
215
216         /// Initializes split-ordered map
217         SplitListMap(
218             size_t nItemCount           ///< estimated average item count
219             , size_t nLoadFactor = 1    ///< load factor - average item count per bucket. Small integer up to 10, default is 1.
220             )
221             : base_class( nItemCount, nLoadFactor )
222         {}
223
224     public:
225         /// Inserts new node with key and default value
226         /**
227             The function creates a node with \p key and default value, and then inserts the node created into the map.
228
229             Preconditions:
230             - The \ref key_type should be constructible from value of type \p K.
231                 In trivial case, \p K is equal to \ref key_type.
232             - The \ref mapped_type should be default-constructible.
233
234             Returns \p true if inserting successful, \p false otherwise.
235         */
236         template <typename K>
237         bool insert( K const& key )
238         {
239             //TODO: pass arguments by reference (make_pair makes copy)
240             return base_class::insert( std::make_pair( key, mapped_type() ) );
241         }
242
243         /// Inserts new node
244         /**
245             The function creates a node with copy of \p val value
246             and then inserts the node created into the map.
247
248             Preconditions:
249             - The \ref key_type should be constructible from \p key of type \p K.
250             - The \ref mapped_type should be constructible from \p val of type \p V.
251
252             Returns \p true if \p val is inserted into the map, \p false otherwise.
253         */
254         template <typename K, typename V>
255         bool insert( K const& key, V const& val )
256         {
257             //TODO: pass arguments by reference (make_pair makes copy)
258             return base_class::insert( std::make_pair(key, val) );
259         }
260
261         /// Inserts new node and initialize it by a functor
262         /**
263             This function inserts new node with key \p key and if inserting is successful then it calls
264             \p func functor with signature
265             \code
266                 struct functor {
267                     void operator()( value_type& item );
268                 };
269             \endcode
270
271             The argument \p item of user-defined functor \p func is the reference
272             to the map's item inserted:
273                 - <tt>item.first</tt> is a const reference to item's key that cannot be changed.
274                 - <tt>item.second</tt> is a reference to item's value that may be changed.
275
276             It should be keep in mind that concurrent modifications of \p <tt>item.second</tt> may be possible.
277
278             The key_type should be constructible from value of type \p K.
279
280             The function allows to split creating of new item into two part:
281             - create item from \p key;
282             - insert new item into the map;
283             - if inserting is successful, initialize the value of item by calling \p func functor
284
285             This can be useful if complete initialization of object of \p mapped_type is heavyweight and
286             it is preferable that the initialization should be completed only if inserting is successful.
287
288             @warning For \ref cds_intrusive_MichaelKVList_hp "MichaelKVList" as the bucket see \ref cds_intrusive_item_creating "insert item troubleshooting".
289             \ref cds_intrusive_LazyKVList_hp "LazyKVList" provides exclusive access to inserted item and does not require any node-level
290             synchronization.
291         */
292         template <typename K, typename Func>
293         bool insert_key( K const& key, Func func )
294         {
295             //TODO: pass arguments by reference (make_pair makes copy)
296             return base_class::insert( std::make_pair( key, mapped_type() ), func );
297         }
298
299         /// For key \p key inserts data of type \p mapped_type created from \p args
300         /**
301             \p key_type should be constructible from type \p K
302
303             Returns \p true if inserting successful, \p false otherwise.
304         */
305         template <typename K, typename... Args>
306         bool emplace( K&& key, Args&&... args )
307         {
308             return base_class::emplace( std::forward<K>(key), std::move(mapped_type(std::forward<Args>(args)...)));
309         }
310
311         /// Ensures that the \p key exists in the map
312         /**
313             The operation performs inserting or changing data with lock-free manner.
314
315             If the \p key not found in the map, then the new item created from \p key
316             is inserted into the map (note that in this case the \ref key_type should be
317             constructible from type \p K).
318             Otherwise, the functor \p func is called with item found.
319             The functor \p Func may be a function with signature:
320             \code
321                 void func( bool bNew, value_type& item );
322             \endcode
323             or a functor:
324             \code
325                 struct my_functor {
326                     void operator()( bool bNew, value_type& item );
327                 };
328             \endcode
329
330             with arguments:
331             - \p bNew - \p true if the item has been inserted, \p false otherwise
332             - \p item - item of the list
333
334             Returns <tt> std::pair<bool, bool> </tt> where \p first is true if operation is successfull,
335             \p second is true if new item has been added or \p false if the item with \p key
336             already is in the list.
337
338             @warning For \ref cds_intrusive_MichaelKVList_hp "MichaelKVList" as the ordered list see \ref cds_intrusive_item_creating "insert item troubleshooting".
339             \ref cds_intrusive_LazyKVList_hp "LazyKVList" provides exclusive access to inserted item and does not require any node-level
340             synchronization.
341         */
342         template <typename K, typename Func>
343         std::pair<bool, bool> ensure( K const& key, Func func )
344         {
345             //TODO: pass arguments by reference (make_pair makes copy)
346             return base_class::ensure( std::make_pair( key, mapped_type() ),
347                 [&func](bool bNew, value_type& item, value_type const& /*val*/) {
348                     func( bNew, item );
349                 } );
350         }
351
352         /// Deletes \p key from the map
353         /** \anchor cds_nonintrusive_SplitListMap_erase_val
354
355             Return \p true if \p key is found and deleted, \p false otherwise
356         */
357         template <typename K>
358         bool erase( K const& key )
359         {
360             return base_class::erase( key );
361         }
362
363         /// Deletes the item from the map using \p pred predicate for searching
364         /**
365             The function is an analog of \ref cds_nonintrusive_SplitListMap_erase_val "erase(K const&)"
366             but \p pred is used for key comparing.
367             \p Less functor has the interface like \p std::less.
368             \p Less must imply the same element order as the comparator used for building the map.
369         */
370         template <typename K, typename Less>
371         bool erase_with( K const& key, Less pred )
372         {
373             return base_class::erase_with( key, cds::details::predicate_wrapper<value_type, Less, key_accessor>() );
374         }
375
376         /// Deletes \p key from the map
377         /** \anchor cds_nonintrusive_SplitListMap_erase_func
378
379             The function searches an item with key \p key, calls \p f functor
380             and deletes the item. If \p key is not found, the functor is not called.
381
382             The functor \p Func interface is:
383             \code
384             struct extractor {
385                 void operator()(value_type& item) { ... }
386             };
387             \endcode
388             The functor may be passed by reference using <tt>boost:ref</tt>
389
390             Return \p true if key is found and deleted, \p false otherwise
391         */
392         template <typename K, typename Func>
393         bool erase( K const& key, Func f )
394         {
395             return base_class::erase( key, f );
396         }
397
398         /// Deletes the item from the map using \p pred predicate for searching
399         /**
400             The function is an analog of \ref cds_nonintrusive_SplitListMap_erase_func "erase(K const&, Func)"
401             but \p pred is used for key comparing.
402             \p Less functor has the interface like \p std::less.
403             \p Less must imply the same element order as the comparator used for building the map.
404         */
405         template <typename K, typename Less, typename Func>
406         bool erase_with( K const& key, Less pred, Func f )
407         {
408             return base_class::erase_with( key, cds::details::predicate_wrapper<value_type, Less, key_accessor>(), f );
409         }
410
411         /// Extracts the item with specified \p key
412         /** \anchor cds_nonintrusive_SplitListMap_hp_extract
413             The function searches an item with key equal to \p key,
414             unlinks it from the map, and returns it in \p dest parameter.
415             If the item with key equal to \p key is not found the function returns \p false.
416
417             Note the compare functor should accept a parameter of type \p K that may be not the same as \p value_type.
418
419             The extracted item is freed automatically when returned \ref guarded_ptr object will be destroyed or released.
420             @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
421
422             Usage:
423             \code
424             typedef cds::container::SplitListMap< your_template_args > splitlist_map;
425             splitlist_map theMap;
426             // ...
427             {
428                 splitlist_map::guarded_ptr gp;
429                 theMap.extract( gp, 5 );
430                 // Deal with gp
431                 // ...
432
433                 // Destructor of gp releases internal HP guard
434             }
435             \endcode
436         */
437         template <typename K>
438         bool extract( guarded_ptr& dest, K const& key )
439         {
440             return base_class::extract_( dest.guard(), key );
441         }
442
443         /// Extracts the item using compare functor \p pred
444         /**
445             The function is an analog of \ref cds_nonintrusive_SplitListMap_hp_extract "extract(guarded_ptr&, K const&)"
446             but \p pred predicate is used for key comparing.
447
448             \p Less functor has the semantics like \p std::less but should take arguments of type \ref value_type and \p K
449             in any order.
450             \p pred must imply the same element order as the comparator used for building the map.
451         */
452         template <typename K, typename Less>
453         bool extract_with( guarded_ptr& dest, K const& key, Less pred )
454         {
455             return base_class::extract_with_( dest.guard(), key, cds::details::predicate_wrapper<value_type, Less, key_accessor>() );
456         }
457
458         /// Finds the key \p key
459         /** \anchor cds_nonintrusive_SplitListMap_find_cfunc
460
461             The function searches the item with key equal to \p key and calls the functor \p f for item found.
462             The interface of \p Func functor is:
463             \code
464             struct functor {
465                 void operator()( value_type& item );
466             };
467             \endcode
468             where \p item is the item found.
469
470             The functor may change \p item.second. Note that the functor is only guarantee
471             that \p item cannot be disposed during functor is executing.
472             The functor does not serialize simultaneous access to the map's \p item. If such access is
473             possible you must provide your own synchronization schema on item level to exclude unsafe item modifications.
474
475             The function returns \p true if \p key is found, \p false otherwise.
476         */
477         template <typename K, typename Func>
478         bool find( K const& key, Func f )
479         {
480             return base_class::find( key, [&f](value_type& pair, K const&){ f( pair ); } );
481         }
482
483         /// Finds the key \p val using \p pred predicate for searching
484         /**
485             The function is an analog of \ref cds_nonintrusive_SplitListMap_find_cfunc "find(K const&, Func)"
486             but \p pred is used for key comparing.
487             \p Less functor has the interface like \p std::less.
488             \p Less must imply the same element order as the comparator used for building the map.
489         */
490         template <typename K, typename Less, typename Func>
491         bool find_with( K const& key, Less pred, Func f )
492         {
493             return base_class::find_with( key,
494                 cds::details::predicate_wrapper<value_type, Less, key_accessor>(),
495                 [&f](value_type& pair, K const&){ f( pair ); } );
496         }
497
498         /// Finds the key \p key
499         /** \anchor cds_nonintrusive_SplitListMap_find_val
500
501             The function searches the item with key equal to \p key
502             and returns \p true if it is found, and \p false otherwise.
503         */
504         template <typename K>
505         bool find( K const& key )
506         {
507             return base_class::find( key );
508         }
509
510         /// Finds the key \p val using \p pred predicate for searching
511         /**
512             The function is an analog of \ref cds_nonintrusive_SplitListMap_find_val "find(K const&)"
513             but \p pred is used for key comparing.
514             \p Less functor has the interface like \p std::less.
515             \p Less must imply the same element order as the comparator used for building the map.
516         */
517         template <typename K, typename Less>
518         bool find_with( K const& key, Less pred )
519         {
520             return base_class::find( key, cds::details::predicate_wrapper<value_type, Less, key_accessor>() );
521         }
522
523         /// Finds \p key and return the item found
524         /** \anchor cds_nonintrusive_SplitListMap_hp_get
525             The function searches the item with key equal to \p key
526             and assigns the item found to guarded pointer \p ptr.
527             The function returns \p true if \p key is found, and \p false otherwise.
528             If \p key is not found the \p ptr parameter is not changed.
529
530             @note Each \p guarded_ptr object uses one GC's guard which can be limited resource.
531
532             Usage:
533             \code
534             typedef cds::container::SplitListMap< your_template_params >  splitlist_map;
535             splitlist_map theMap;
536             // ...
537             {
538                 splitlist_map::guarded_ptr gp;
539                 if ( theMap.get( gp, 5 )) {
540                     // Deal with gp
541                     //...
542                 }
543                 // Destructor of guarded_ptr releases internal HP guard
544             }
545             \endcode
546
547             Note the compare functor specified for split-list map
548             should accept a parameter of type \p K that can be not the same as \p value_type.
549         */
550         template <typename K>
551         bool get( guarded_ptr& ptr, K const& key )
552         {
553             return base_class::get_( ptr.guard(), key );
554         }
555
556         /// Finds \p key and return the item found
557         /**
558             The function is an analog of \ref cds_nonintrusive_SplitListMap_hp_get "get( guarded_ptr&, K const&)"
559             but \p pred is used for comparing the keys.
560
561             \p Less functor has the semantics like \p std::less but should take arguments of type \ref value_type and \p K
562             in any order.
563             \p pred must imply the same element order as the comparator used for building the map.
564         */
565         template <typename K, typename Less>
566         bool get_with( guarded_ptr& ptr, K const& key, Less pred )
567         {
568             return base_class::get_with_( ptr.guard(), key, cds::details::predicate_wrapper<value_type, Less, key_accessor>() );
569         }
570
571         /// Clears the map (not atomic)
572         void clear()
573         {
574             base_class::clear();
575         }
576
577         /// Checks if the map is empty
578         /**
579             Emptiness is checked by item counting: if item count is zero then the map is empty.
580             Thus, the correct item counting is an important part of the map implementation.
581         */
582         bool empty() const
583         {
584             return base_class::empty();
585         }
586
587         /// Returns item count in the map
588         size_t size() const
589         {
590             return base_class::size();
591         }
592
593         /// Returns internal statistics
594         stat const& statistics() const
595         {
596             return base_class::statistics();
597         }
598     };
599
600
601 }} // namespace cds::container
602
603 #endif // #ifndef __CDS_CONTAINER_SPLIT_LIST_MAP_H