container::SplitListMap refactoring
[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
139     protected:
140         //@cond
141         typedef typename base_class::maker::traits::key_accessor key_accessor;
142         typedef typename base_class::node_type node_type;
143         //@endcond
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     public:
150         /// Forward iterator (see \p SplitListSet::iterator)
151         /**
152             Remember, the iterator <tt>operator -> </tt> and <tt>operator *</tt> returns \ref value_type pointer and reference.
153             To access item key and value use <tt>it->first</tt> and <tt>it->second</tt> respectively.
154         */
155         typedef typename base_class::iterator iterator;
156
157         /// Const forward iterator (see SplitListSet::const_iterator)
158         typedef typename base_class::const_iterator const_iterator;
159
160         /// Returns a forward iterator addressing the first element in a map
161         /**
162             For empty map \code begin() == end() \endcode
163         */
164         iterator begin()
165         {
166             return base_class::begin();
167         }
168
169         /// Returns an iterator that addresses the location succeeding the last element in a map
170         /**
171             Do not use the value returned by <tt>end</tt> function to access any item.
172             The returned value can be used only to control reaching the end of the map.
173             For empty map \code begin() == end() \endcode
174         */
175         iterator end()
176         {
177             return base_class::end();
178         }
179
180         /// Returns a forward const iterator addressing the first element in a map
181         //@{
182         const_iterator begin() const
183         {
184             return base_class::begin();
185         }
186         const_iterator cbegin()
187         {
188             return base_class::cbegin();
189         }
190         //@}
191
192         /// Returns an const iterator that addresses the location succeeding the last element in a map
193         //@{
194         const_iterator end() const
195         {
196             return base_class::end();
197         }
198         const_iterator cend()
199         {
200             return base_class::cend();
201         }
202         //@}
203
204     public:
205         /// Initializes split-ordered map of default capacity
206         /**
207             The default capacity is defined in bucket table constructor.
208             See \p intrusive::split_list::expandable_bucket_table, \p intrusive::split_list::static_bucket_table
209             which selects by \p intrusive::split_list::traits::dynamic_bucket_table.
210         */
211         SplitListMap()
212             : base_class()
213         {}
214
215         /// Initializes split-ordered map
216         SplitListMap(
217             size_t nItemCount           ///< estimated average item count
218             , size_t nLoadFactor = 1    ///< load factor - average item count per bucket. Small integer up to 10, default is 1.
219             )
220             : base_class( nItemCount, nLoadFactor )
221         {}
222
223     public:
224         /// Inserts new node with key and default value
225         /**
226             The function creates a node with \p key and default value, and then inserts the node created into the map.
227
228             Preconditions:
229             - The \ref key_type should be constructible from value of type \p K.
230                 In trivial case, \p K is equal to \ref key_type.
231             - The \ref mapped_type should be default-constructible.
232
233             Returns \p true if inserting successful, \p false otherwise.
234         */
235         template <typename K>
236         bool insert( K const& key )
237         {
238             //TODO: pass arguments by reference (make_pair makes copy)
239             return base_class::insert( std::make_pair( key, mapped_type() ) );
240         }
241
242         /// Inserts new node
243         /**
244             The function creates a node with copy of \p val value
245             and then inserts the node created into the map.
246
247             Preconditions:
248             - The \ref key_type should be constructible from \p key of type \p K.
249             - The \ref mapped_type should be constructible from \p val of type \p V.
250
251             Returns \p true if \p val is inserted into the map, \p false otherwise.
252         */
253         template <typename K, typename V>
254         bool insert( K const& key, V const& val )
255         {
256             //TODO: pass arguments by reference (make_pair makes copy)
257             return base_class::insert( std::make_pair(key, val) );
258         }
259
260         /// Inserts new node and initialize it by a functor
261         /**
262             This function inserts new node with key \p key and if inserting is successful then it calls
263             \p func functor with signature
264             \code
265                 struct functor {
266                     void operator()( value_type& item );
267                 };
268             \endcode
269
270             The argument \p item of user-defined functor \p func is the reference
271             to the map's item inserted:
272                 - <tt>item.first</tt> is a const reference to item's key that cannot be changed.
273                 - <tt>item.second</tt> is a reference to item's value that may be changed.
274
275             It should be keep in mind that concurrent modifications of \p <tt>item.second</tt> may be possible.
276
277             The key_type should be constructible from value of type \p K.
278
279             The function allows to split creating of new item into two part:
280             - create item from \p key;
281             - insert new item into the map;
282             - if inserting is successful, initialize the value of item by calling \p func functor
283
284             This can be useful if complete initialization of object of \p mapped_type is heavyweight and
285             it is preferable that the initialization should be completed only if inserting is successful.
286
287             @warning For \ref cds_intrusive_MichaelKVList_hp "MichaelKVList" as the bucket see \ref cds_intrusive_item_creating "insert item troubleshooting".
288             \ref cds_intrusive_LazyKVList_hp "LazyKVList" provides exclusive access to inserted item and does not require any node-level
289             synchronization.
290         */
291         template <typename K, typename Func>
292         bool insert_key( K const& key, Func func )
293         {
294             //TODO: pass arguments by reference (make_pair makes copy)
295             return base_class::insert( std::make_pair( key, mapped_type() ), func );
296         }
297
298         /// For key \p key inserts data of type \p mapped_type created from \p args
299         /**
300             \p key_type should be constructible from type \p K
301
302             Returns \p true if inserting successful, \p false otherwise.
303         */
304         template <typename K, typename... Args>
305         bool emplace( K&& key, Args&&... args )
306         {
307             return base_class::emplace( std::forward<K>(key), std::move(mapped_type(std::forward<Args>(args)...)));
308         }
309
310         /// Ensures that the \p key exists in the map
311         /**
312             The operation performs inserting or changing data with lock-free manner.
313
314             If the \p key not found in the map, then the new item created from \p key
315             is inserted into the map (note that in this case the \ref key_type should be
316             constructible from type \p K).
317             Otherwise, the functor \p func is called with item found.
318             The functor \p Func may be a function with signature:
319             \code
320                 void func( bool bNew, value_type& item );
321             \endcode
322             or a functor:
323             \code
324                 struct my_functor {
325                     void operator()( bool bNew, value_type& item );
326                 };
327             \endcode
328
329             with arguments:
330             - \p bNew - \p true if the item has been inserted, \p false otherwise
331             - \p item - item of the list
332
333             Returns <tt> std::pair<bool, bool> </tt> where \p first is true if operation is successfull,
334             \p second is true if new item has been added or \p false if the item with \p key
335             already is in the list.
336
337             @warning For \ref cds_intrusive_MichaelKVList_hp "MichaelKVList" as the bucket see \ref cds_intrusive_item_creating "insert item troubleshooting".
338             \ref cds_intrusive_LazyKVList_hp "LazyKVList" provides exclusive access to inserted item and does not require any node-level
339             synchronization.
340         */
341         template <typename K, typename Func>
342         std::pair<bool, bool> ensure( K const& key, Func func )
343         {
344             //TODO: pass arguments by reference (make_pair makes copy)
345             return base_class::ensure( std::make_pair( key, mapped_type() ),
346                 [&func](bool bNew, value_type& item, value_type const& /*val*/) {
347                     func( bNew, item );
348                 } );
349         }
350
351         /// Deletes \p key from the map
352         /** \anchor cds_nonintrusive_SplitListMap_erase_val
353
354             Return \p true if \p key is found and deleted, \p false otherwise
355         */
356         template <typename K>
357         bool erase( K const& key )
358         {
359             return base_class::erase( key );
360         }
361
362         /// Deletes the item from the map using \p pred predicate for searching
363         /**
364             The function is an analog of \ref cds_nonintrusive_SplitListMap_erase_val "erase(K const&)"
365             but \p pred is used for key comparing.
366             \p Less functor has the interface like \p std::less.
367             \p Less must imply the same element order as the comparator used for building the map.
368         */
369         template <typename K, typename Less>
370         bool erase_with( K const& key, Less pred )
371         {
372             return base_class::erase_with( key, cds::details::predicate_wrapper<value_type, Less, key_accessor>() );
373         }
374
375         /// Deletes \p key from the map
376         /** \anchor cds_nonintrusive_SplitListMap_erase_func
377
378             The function searches an item with key \p key, calls \p f functor
379             and deletes the item. If \p key is not found, the functor is not called.
380
381             The functor \p Func interface is:
382             \code
383             struct extractor {
384                 void operator()(value_type& item) { ... }
385             };
386             \endcode
387             The functor may be passed by reference using <tt>boost:ref</tt>
388
389             Return \p true if key is found and deleted, \p false otherwise
390         */
391         template <typename K, typename Func>
392         bool erase( K const& key, Func f )
393         {
394             return base_class::erase( key, f );
395         }
396
397         /// Deletes the item from the map using \p pred predicate for searching
398         /**
399             The function is an analog of \ref cds_nonintrusive_SplitListMap_erase_func "erase(K const&, Func)"
400             but \p pred is used for key comparing.
401             \p Less functor has the interface like \p std::less.
402             \p Less must imply the same element order as the comparator used for building the map.
403         */
404         template <typename K, typename Less, typename Func>
405         bool erase_with( K const& key, Less pred, Func f )
406         {
407             return base_class::erase_with( key, cds::details::predicate_wrapper<value_type, Less, key_accessor>(), f );
408         }
409
410         /// Extracts the item with specified \p key
411         /** \anchor cds_nonintrusive_SplitListMap_hp_extract
412             The function searches an item with key equal to \p key,
413             unlinks it from the map, and returns it in \p dest parameter.
414             If the item with key equal to \p key is not found the function returns \p false.
415
416             Note the compare functor should accept a parameter of type \p K that may be not the same as \p value_type.
417
418             The extracted item is freed automatically when returned \ref guarded_ptr object will be destroyed or released.
419             @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
420
421             Usage:
422             \code
423             typedef cds::container::SplitListMap< your_template_args > splitlist_map;
424             splitlist_map theMap;
425             // ...
426             {
427                 splitlist_map::guarded_ptr gp;
428                 theMap.extract( gp, 5 );
429                 // Deal with gp
430                 // ...
431
432                 // Destructor of gp releases internal HP guard
433             }
434             \endcode
435         */
436         template <typename K>
437         bool extract( guarded_ptr& dest, K const& key )
438         {
439             return base_class::extract_( dest.guard(), key );
440         }
441
442         /// Extracts the item using compare functor \p pred
443         /**
444             The function is an analog of \ref cds_nonintrusive_SplitListMap_hp_extract "extract(guarded_ptr&, K const&)"
445             but \p pred predicate is used for key comparing.
446
447             \p Less functor has the semantics like \p std::less but should take arguments of type \ref value_type and \p K
448             in any order.
449             \p pred must imply the same element order as the comparator used for building the map.
450         */
451         template <typename K, typename Less>
452         bool extract_with( guarded_ptr& dest, K const& key, Less pred )
453         {
454             return base_class::extract_with_( dest.guard(), key, cds::details::predicate_wrapper<value_type, Less, key_accessor>() );
455         }
456
457         /// Finds the key \p key
458         /** \anchor cds_nonintrusive_SplitListMap_find_cfunc
459
460             The function searches the item with key equal to \p key and calls the functor \p f for item found.
461             The interface of \p Func functor is:
462             \code
463             struct functor {
464                 void operator()( value_type& item );
465             };
466             \endcode
467             where \p item is the item found.
468
469             The functor may change \p item.second. Note that the functor is only guarantee
470             that \p item cannot be disposed during functor is executing.
471             The functor does not serialize simultaneous access to the map's \p item. If such access is
472             possible you must provide your own synchronization schema on item level to exclude unsafe item modifications.
473
474             The function returns \p true if \p key is found, \p false otherwise.
475         */
476         template <typename K, typename Func>
477         bool find( K const& key, Func f )
478         {
479             return base_class::find( key, [&f](value_type& pair, K const&){ f( pair ); } );
480         }
481
482         /// Finds the key \p val using \p pred predicate for searching
483         /**
484             The function is an analog of \ref cds_nonintrusive_SplitListMap_find_cfunc "find(K const&, Func)"
485             but \p pred is used for key comparing.
486             \p Less functor has the interface like \p std::less.
487             \p Less must imply the same element order as the comparator used for building the map.
488         */
489         template <typename K, typename Less, typename Func>
490         bool find_with( K const& key, Less pred, Func f )
491         {
492             return base_class::find_with( key,
493                 cds::details::predicate_wrapper<value_type, Less, key_accessor>(),
494                 [&f](value_type& pair, K const&){ f( pair ); } );
495         }
496
497         /// Finds the key \p key
498         /** \anchor cds_nonintrusive_SplitListMap_find_val
499
500             The function searches the item with key equal to \p key
501             and returns \p true if it is found, and \p false otherwise.
502         */
503         template <typename K>
504         bool find( K const& key )
505         {
506             return base_class::find( key );
507         }
508
509         /// Finds the key \p val using \p pred predicate for searching
510         /**
511             The function is an analog of \ref cds_nonintrusive_SplitListMap_find_val "find(K const&)"
512             but \p pred is used for key comparing.
513             \p Less functor has the interface like \p std::less.
514             \p Less must imply the same element order as the comparator used for building the map.
515         */
516         template <typename K, typename Less>
517         bool find_with( K const& key, Less pred )
518         {
519             return base_class::find( key, cds::details::predicate_wrapper<value_type, Less, key_accessor>() );
520         }
521
522         /// Finds \p key and return the item found
523         /** \anchor cds_nonintrusive_SplitListMap_hp_get
524             The function searches the item with key equal to \p key
525             and assigns the item found to guarded pointer \p ptr.
526             The function returns \p true if \p key is found, and \p false otherwise.
527             If \p key is not found the \p ptr parameter is not changed.
528
529             @note Each \p guarded_ptr object uses one GC's guard which can be limited resource.
530
531             Usage:
532             \code
533             typedef cds::container::SplitListMap< your_template_params >  splitlist_map;
534             splitlist_map theMap;
535             // ...
536             {
537                 splitlist_map::guarded_ptr gp;
538                 if ( theMap.get( gp, 5 )) {
539                     // Deal with gp
540                     //...
541                 }
542                 // Destructor of guarded_ptr releases internal HP guard
543             }
544             \endcode
545
546             Note the compare functor specified for split-list map
547             should accept a parameter of type \p K that can be not the same as \p value_type.
548         */
549         template <typename K>
550         bool get( guarded_ptr& ptr, K const& key )
551         {
552             return base_class::get_( ptr.guard(), key );
553         }
554
555         /// Finds \p key and return the item found
556         /**
557             The function is an analog of \ref cds_nonintrusive_SplitListMap_hp_get "get( guarded_ptr&, K const&)"
558             but \p pred is used for comparing the keys.
559
560             \p Less functor has the semantics like \p std::less but should take arguments of type \ref value_type and \p K
561             in any order.
562             \p pred must imply the same element order as the comparator used for building the map.
563         */
564         template <typename K, typename Less>
565         bool get_with( guarded_ptr& ptr, K const& key, Less pred )
566         {
567             return base_class::get_with_( ptr.guard(), key, cds::details::predicate_wrapper<value_type, Less, key_accessor>() );
568         }
569
570         /// Clears the map (not atomic)
571         void clear()
572         {
573             base_class::clear();
574         }
575
576         /// Checks if the map is empty
577         /**
578             Emptiness is checked by item counting: if item count is zero then the map is empty.
579             Thus, the correct item counting is an important part of the map implementation.
580         */
581         bool empty() const
582         {
583             return base_class::empty();
584         }
585
586         /// Returns item count in the map
587         size_t size() const
588         {
589             return base_class::size();
590         }
591     };
592
593
594 }} // namespace cds::container
595
596 #endif // #ifndef __CDS_CONTAINER_SPLIT_LIST_MAP_H