d033d24cb83f6a3ebab43c0c8b5bd468861d34b0
[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 - type traits, default is split_list::type_traits. Instead of declaring split_list::type_traits -based
26             struct you may apply option-based notation with 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 gc::HP GC
38         and MichaelList as ordered list implementation. Your map should map \p int key to <tt>std::string</tt> 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 for the map key and a comparing functor for 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 <tt>cds::contaner::michael_list_tag</tt> 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::type_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::type_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 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 using 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 type_traits parts, optional ones is the default and they are inherited
98         from cds::container::split_list::type_traits.
99         The <b>cds</b> library contains many other options for deep tuning of behavior of the split-list and
100         ordered-list containers.
101     */
102     template <
103         class GC,
104         typename Key,
105         typename Value,
106 #ifdef CDS_DOXYGEN_INVOKED
107         class Traits = split_list::type_traits
108 #else
109         class Traits
110 #endif
111     >
112     class SplitListMap:
113         protected container::SplitListSet<
114             GC,
115             std::pair<Key const, Value>,
116             split_list::details::wrap_map_traits<Key, Value, Traits>
117         >
118     {
119         //@cond
120         typedef container::SplitListSet<
121             GC,
122             std::pair<Key const, Value>,
123             split_list::details::wrap_map_traits<Key, Value, Traits>
124         >  base_class;
125         //@endcond
126
127     public:
128         typedef typename base_class::gc gc              ;   ///< Garbage collector
129         typedef Key                     key_type        ;   ///< key type
130         typedef Value                   mapped_type     ;   ///< type of value stored in the map
131         typedef Traits                  options         ;   ///< \p Traits template argument
132
133         typedef std::pair<key_type const, mapped_type>  value_type  ;   ///< key-value pair type
134         typedef typename base_class::ordered_list       ordered_list;   ///< Underlying ordered list class
135         typedef typename base_class::key_comparator     key_comparator  ;   ///< key compare functor
136
137         typedef typename base_class::hash           hash            ;   ///< Hash functor for \ref key_type
138         typedef typename base_class::item_counter   item_counter    ;   ///< Item counter type
139
140     protected:
141         //@cond
142         typedef typename base_class::maker::type_traits::key_accessor key_accessor;
143         typedef typename base_class::node_type node_type;
144
145     public:
146         /// Guarded pointer
147         typedef cds::gc::guarded_ptr< gc, node_type, value_type, details::guarded_ptr_cast_set<node_type, value_type> > guarded_ptr;
148
149
150 #   ifndef CDS_CXX11_LAMBDA_SUPPORT
151         template <typename Func>
152         class ensure_functor_wrapper: protected cds::details::functor_wrapper<Func>
153         {
154             typedef cds::details::functor_wrapper<Func> base_class;
155         public:
156             ensure_functor_wrapper() {}
157             ensure_functor_wrapper( Func f ): base_class(f) {}
158
159             template <typename Q>
160             void operator()( bool bNew, value_type& item, const Q& /*val*/ )
161             {
162                 base_class::get()( bNew, item );
163             }
164         };
165
166         template <typename Func>
167         class find_functor_wrapper: protected cds::details::functor_wrapper<Func>
168         {
169             typedef cds::details::functor_wrapper<Func> base_class;
170         public:
171             find_functor_wrapper() {}
172             find_functor_wrapper( Func f ): base_class(f) {}
173
174             template <typename Q>
175             void operator()( value_type& pair, Q const& /*val*/ )
176             {
177                 base_class::get()( pair );
178             }
179         };
180 #   endif   // ifndef CDS_CXX11_LAMBDA_SUPPORT
181         //@endcond
182
183     public:
184         /// Forward iterator (see SplitListSet::iterator)
185         /**
186             Remember, the iterator <tt>operator -> </tt> and <tt>operator *</tt> returns \ref value_type pointer and reference.
187             To access item key and value use <tt>it->first</tt> and <tt>it->second</tt> respectively.
188         */
189         typedef typename base_class::iterator iterator;
190
191         /// Const forward iterator (see SplitListSet::const_iterator)
192         typedef typename base_class::const_iterator const_iterator;
193
194         /// Returns a forward iterator addressing the first element in a map
195         /**
196             For empty map \code begin() == end() \endcode
197         */
198         iterator begin()
199         {
200             return base_class::begin();
201         }
202
203         /// Returns an iterator that addresses the location succeeding the last element in a map
204         /**
205             Do not use the value returned by <tt>end</tt> function to access any item.
206             The returned value can be used only to control reaching the end of the map.
207             For empty map \code begin() == end() \endcode
208         */
209         iterator end()
210         {
211             return base_class::end();
212         }
213
214         /// Returns a forward const iterator addressing the first element in a map
215         //@{
216         const_iterator begin() const
217         {
218             return base_class::begin();
219         }
220         const_iterator cbegin()
221         {
222             return base_class::cbegin();
223         }
224         //@}
225
226         /// Returns an const iterator that addresses the location succeeding the last element in a map
227         //@{
228         const_iterator end() const
229         {
230             return base_class::end();
231         }
232         const_iterator cend()
233         {
234             return base_class::cend();
235         }
236         //@}
237
238     public:
239         /// Initializes split-ordered map of default capacity
240         /**
241             The default capacity is defined in bucket table constructor.
242             See intrusive::split_list::expandable_bucket_table, intrusive::split_list::static_bucket_table
243             which selects by intrusive::split_list::dynamic_bucket_table option.
244         */
245         SplitListMap()
246             : base_class()
247         {}
248
249         /// Initializes split-ordered map
250         SplitListMap(
251             size_t nItemCount           ///< estimate average item count
252             , size_t nLoadFactor = 1    ///< load factor - average item count per bucket. Small integer up to 10, default is 1.
253             )
254             : base_class( nItemCount, nLoadFactor )
255         {}
256
257     public:
258         /// Inserts new node with key and default value
259         /**
260             The function creates a node with \p key and default value, and then inserts the node created into the map.
261
262             Preconditions:
263             - The \ref key_type should be constructible from value of type \p K.
264                 In trivial case, \p K is equal to \ref key_type.
265             - The \ref mapped_type should be default-constructible.
266
267             Returns \p true if inserting successful, \p false otherwise.
268         */
269         template <typename K>
270         bool insert( K const& key )
271         {
272             //TODO: pass arguments by reference (make_pair makes copy)
273             return base_class::insert( std::make_pair( key, mapped_type() ) );
274         }
275
276         /// Inserts new node
277         /**
278             The function creates a node with copy of \p val value
279             and then inserts the node created into the map.
280
281             Preconditions:
282             - The \ref key_type should be constructible from \p key of type \p K.
283             - The \ref mapped_type should be constructible from \p val of type \p V.
284
285             Returns \p true if \p val is inserted into the map, \p false otherwise.
286         */
287         template <typename K, typename V>
288         bool insert( K const& key, V const& val )
289         {
290             //TODO: pass arguments by reference (make_pair makes copy)
291             return base_class::insert( std::make_pair(key, val) );
292         }
293
294         /// Inserts new node and initialize it by a functor
295         /**
296             This function inserts new node with key \p key and if inserting is successful then it calls
297             \p func functor with signature
298             \code
299                 struct functor {
300                     void operator()( value_type& item );
301                 };
302             \endcode
303
304             The argument \p item of user-defined functor \p func is the reference
305             to the map's item inserted:
306                 - <tt>item.first</tt> is a const reference to item's key that cannot be changed.
307                 - <tt>item.second</tt> is a reference to item's value that may be changed.
308
309             It should be keep in mind that concurrent modifications of \p <tt>item.second</tt> may be possible.
310             User-defined functor \p func should guarantee that during changing item's value no any other changes
311             could be made on this \p item by concurrent threads.
312
313             The user-defined functor can be passed by reference using <tt>boost::ref</tt>
314             and it is called only if inserting is successful.
315
316             The key_type should be constructible from value of type \p K.
317
318             The function allows to split creating of new item into two part:
319             - create item from \p key;
320             - insert new item into the map;
321             - if inserting is successful, initialize the value of item by calling \p func functor
322
323             This can be useful if complete initialization of object of \p mapped_type is heavyweight and
324             it is preferable that the initialization should be completed only if inserting is successful.
325         */
326         template <typename K, typename Func>
327         bool insert_key( K const& key, Func func )
328         {
329             //TODO: pass arguments by reference (make_pair makes copy)
330             return base_class::insert( std::make_pair( key, mapped_type() ), func );
331         }
332
333 #   ifdef CDS_EMPLACE_SUPPORT
334         /// For key \p key inserts data of type \ref mapped_type constructed with <tt>std::forward<Args>(args)...</tt>
335         /**
336             \p key_type should be constructible from type \p K
337
338             Returns \p true if inserting successful, \p false otherwise.
339
340             This function is available only for compiler that supports
341             variadic template and move semantics
342         */
343         template <typename K, typename... Args>
344         bool emplace( K&& key, Args&&... args )
345         {
346             return base_class::emplace( std::forward<K>(key), std::move(mapped_type(std::forward<Args>(args)...)));
347         }
348 #   endif
349
350
351         /// Ensures that the \p key exists in the map
352         /**
353             The operation performs inserting or changing data with lock-free manner.
354
355             If the \p key not found in the map, then the new item created from \p key
356             is inserted into the map (note that in this case the \ref key_type should be
357             constructible from type \p K).
358             Otherwise, the functor \p func is called with item found.
359             The functor \p Func may be a function with signature:
360             \code
361                 void func( bool bNew, value_type& item );
362             \endcode
363             or a functor:
364             \code
365                 struct my_functor {
366                     void operator()( bool bNew, value_type& item );
367                 };
368             \endcode
369
370             with arguments:
371             - \p bNew - \p true if the item has been inserted, \p false otherwise
372             - \p item - item of the list
373
374             The functor may change any fields of the \p item.second that is \ref mapped_type;
375             however, \p func must guarantee that during changing no any other modifications
376             could be made on this item by concurrent threads.
377
378             You may pass \p func argument by reference using <tt>boost::ref</tt>.
379
380             Returns <tt> std::pair<bool, bool> </tt> where \p first is true if operation is successfull,
381             \p second is true if new item has been added or \p false if the item with \p key
382             already is in the list.
383         */
384         template <typename K, typename Func>
385         std::pair<bool, bool> ensure( K const& key, Func func )
386         {
387             //TODO: pass arguments by reference (make_pair makes copy)
388 #   ifdef CDS_CXX11_LAMBDA_SUPPORT
389             return base_class::ensure( std::make_pair( key, mapped_type() ),
390                 [&func](bool bNew, value_type& item, value_type const& /*val*/) {
391                     cds::unref(func)( bNew, item );
392                 } );
393 #   else
394             ensure_functor_wrapper<Func> fw( func );
395             return base_class::ensure( std::make_pair( key, mapped_type() ), cds::ref(fw) );
396 #   endif
397         }
398
399         /// Deletes \p key from the map
400         /** \anchor cds_nonintrusive_SplitListMap_erase_val
401
402             Return \p true if \p key is found and deleted, \p false otherwise
403         */
404         template <typename K>
405         bool erase( K const& key )
406         {
407             return base_class::erase( key );
408         }
409
410         /// Deletes the item from the map using \p pred predicate for searching
411         /**
412             The function is an analog of \ref cds_nonintrusive_SplitListMap_erase_val "erase(K const&)"
413             but \p pred is used for key comparing.
414             \p Less functor has the interface like \p std::less.
415             \p Less must imply the same element order as the comparator used for building the map.
416         */
417         template <typename K, typename Less>
418         bool erase_with( K const& key, Less pred )
419         {
420             return base_class::erase_with( key, cds::details::predicate_wrapper<value_type, Less, key_accessor>() );
421         }
422
423         /// Deletes \p key from the map
424         /** \anchor cds_nonintrusive_SplitListMap_erase_func
425
426             The function searches an item with key \p key, calls \p f functor
427             and deletes the item. If \p key is not found, the functor is not called.
428
429             The functor \p Func interface is:
430             \code
431             struct extractor {
432                 void operator()(value_type& item) { ... }
433             };
434             \endcode
435             The functor may be passed by reference using <tt>boost:ref</tt>
436
437             Return \p true if key is found and deleted, \p false otherwise
438         */
439         template <typename K, typename Func>
440         bool erase( K const& key, Func f )
441         {
442             return base_class::erase( key, f );
443         }
444
445         /// Deletes the item from the map using \p pred predicate for searching
446         /**
447             The function is an analog of \ref cds_nonintrusive_SplitListMap_erase_func "erase(K const&, Func)"
448             but \p pred is used for key comparing.
449             \p Less functor has the interface like \p std::less.
450             \p Less must imply the same element order as the comparator used for building the map.
451         */
452         template <typename K, typename Less, typename Func>
453         bool erase_with( K const& key, Less pred, Func f )
454         {
455             return base_class::erase_with( key, cds::details::predicate_wrapper<value_type, Less, key_accessor>(), f );
456         }
457
458         /// Extracts the item with specified \p key
459         /** \anchor cds_nonintrusive_SplitListMap_hp_extract
460             The function searches an item with key equal to \p key,
461             unlinks it from the map, and returns it in \p dest parameter.
462             If the item with key equal to \p key is not found the function returns \p false.
463
464             Note the compare functor should accept a parameter of type \p K that may be not the same as \p value_type.
465
466             The extracted item is freed automatically when returned \ref guarded_ptr object will be destroyed or released.
467             @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
468
469             Usage:
470             \code
471             typedef cds::container::SplitListMap< your_template_args > splitlist_map;
472             splitlist_map theMap;
473             // ...
474             {
475                 splitlist_map::guarded_ptr gp;
476                 theMap.extract( gp, 5 );
477                 // Deal with gp
478                 // ...
479
480                 // Destructor of gp releases internal HP guard
481             }
482             \endcode
483         */
484         template <typename K>
485         bool extract( guarded_ptr& dest, K const& key )
486         {
487             return base_class::extract_( dest.guard(), key );
488         }
489
490         /// Extracts the item using compare functor \p pred
491         /**
492             The function is an analog of \ref cds_nonintrusive_SplitListMap_hp_extract "extract(guarded_ptr&, K const&)"
493             but \p pred predicate is used for key comparing.
494
495             \p Less functor has the semantics like \p std::less but should take arguments of type \ref value_type and \p K
496             in any order.
497             \p pred must imply the same element order as the comparator used for building the map.
498         */
499         template <typename K, typename Less>
500         bool extract_with( guarded_ptr& dest, K const& key, Less pred )
501         {
502             return base_class::extract_with_( dest.guard(), key, cds::details::predicate_wrapper<value_type, Less, key_accessor>() );
503         }
504
505         /// Finds the key \p key
506         /** \anchor cds_nonintrusive_SplitListMap_find_cfunc
507
508             The function searches the item with key equal to \p key and calls the functor \p f for item found.
509             The interface of \p Func functor is:
510             \code
511             struct functor {
512                 void operator()( value_type& item );
513             };
514             \endcode
515             where \p item is the item found.
516
517             You may pass \p f argument by reference using <tt>boost::ref</tt> or cds::ref.
518
519             The functor may change \p item.second. Note that the functor is only guarantee
520             that \p item cannot be disposed during functor is executing.
521             The functor does not serialize simultaneous access to the map's \p item. If such access is
522             possible you must provide your own synchronization schema on item level to exclude unsafe item modifications.
523
524             The function returns \p true if \p key is found, \p false otherwise.
525         */
526         template <typename K, typename Func>
527         bool find( K const& key, Func f )
528         {
529 #   ifdef CDS_CXX11_LAMBDA_SUPPORT
530             return base_class::find( key, [&f](value_type& pair, K const&){ cds::unref(f)( pair ); } );
531 #   else
532             find_functor_wrapper<Func> fw(f);
533             return base_class::find( key, cds::ref(fw) );
534 #   endif
535         }
536
537         /// Finds the key \p val using \p pred predicate for searching
538         /**
539             The function is an analog of \ref cds_nonintrusive_SplitListMap_find_cfunc "find(K const&, Func)"
540             but \p pred is used for key comparing.
541             \p Less functor has the interface like \p std::less.
542             \p Less must imply the same element order as the comparator used for building the map.
543         */
544         template <typename K, typename Less, typename Func>
545         bool find_with( K const& key, Less pred, Func f )
546         {
547 #   ifdef CDS_CXX11_LAMBDA_SUPPORT
548             return base_class::find_with( key,
549                 cds::details::predicate_wrapper<value_type, Less, key_accessor>(),
550                 [&f](value_type& pair, K const&){ cds::unref(f)( pair ); } );
551 #   else
552             find_functor_wrapper<Func> fw(f);
553             return base_class::find_with( key, cds::details::predicate_wrapper<value_type, Less, key_accessor>(), cds::ref(fw) );
554 #   endif
555         }
556
557         /// Finds the key \p key
558         /** \anchor cds_nonintrusive_SplitListMap_find_val
559
560             The function searches the item with key equal to \p key
561             and returns \p true if it is found, and \p false otherwise.
562         */
563         template <typename K>
564         bool find( K const& key )
565         {
566             return base_class::find( key );
567         }
568
569         /// Finds the key \p val using \p pred predicate for searching
570         /**
571             The function is an analog of \ref cds_nonintrusive_SplitListMap_find_val "find(K const&)"
572             but \p pred is used for key comparing.
573             \p Less functor has the interface like \p std::less.
574             \p Less must imply the same element order as the comparator used for building the map.
575         */
576         template <typename K, typename Less>
577         bool find_with( K const& key, Less pred )
578         {
579             return base_class::find( key, cds::details::predicate_wrapper<value_type, Less, key_accessor>() );
580         }
581
582         /// Finds \p key and return the item found
583         /** \anchor cds_nonintrusive_SplitListMap_hp_get
584             The function searches the item with key equal to \p key
585             and assigns the item found to guarded pointer \p ptr.
586             The function returns \p true if \p key is found, and \p false otherwise.
587             If \p key is not found the \p ptr parameter is not changed.
588
589             @note Each \p guarded_ptr object uses one GC's guard which can be limited resource.
590
591             Usage:
592             \code
593             typedef cds::container::SplitListMap< your_template_params >  splitlist_map;
594             splitlist_map theMap;
595             // ...
596             {
597                 splitlist_map::guarded_ptr gp;
598                 if ( theMap.get( gp, 5 )) {
599                     // Deal with gp
600                     //...
601                 }
602                 // Destructor of guarded_ptr releases internal HP guard
603             }
604             \endcode
605
606             Note the compare functor specified for split-list map
607             should accept a parameter of type \p K that can be not the same as \p value_type.
608         */
609         template <typename K>
610         bool get( guarded_ptr& ptr, K const& key )
611         {
612             return base_class::get_( ptr.guard(), key );
613         }
614
615         /// Finds \p key and return the item found
616         /**
617             The function is an analog of \ref cds_nonintrusive_SplitListMap_hp_get "get( guarded_ptr&, K const&)"
618             but \p pred is used for comparing the keys.
619
620             \p Less functor has the semantics like \p std::less but should take arguments of type \ref value_type and \p K
621             in any order.
622             \p pred must imply the same element order as the comparator used for building the map.
623         */
624         template <typename K, typename Less>
625         bool get_with( guarded_ptr& ptr, K const& key, Less pred )
626         {
627             return base_class::get_with_( ptr.guard(), key, cds::details::predicate_wrapper<value_type, Less, key_accessor>() );
628         }
629
630         /// Clears the map (non-atomic)
631         /**
632             The function unlink all items from the map.
633             The function is not atomic and not lock-free and should be used for debugging only.
634         */
635         void clear()
636         {
637             base_class::clear();
638         }
639
640         /// Checks if the map is empty
641         /**
642             Emptiness is checked by item counting: if item count is zero then the map is empty.
643             Thus, the correct item counting is an important part of the map implementation.
644         */
645         bool empty() const
646         {
647             return base_class::empty();
648         }
649
650         /// Returns item count in the map
651         size_t size() const
652         {
653             return base_class::size();
654         }
655     };
656
657
658 }} // namespace cds::container
659
660 #endif // #ifndef __CDS_CONTAINER_SPLIT_LIST_MAP_H