b30bff95874928601f92abc4a47f95602c275212
[libcds.git] / cds / intrusive / michael_set_nogc.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-2016
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_INTRUSIVE_MICHAEL_SET_NOGC_H
32 #define CDSLIB_INTRUSIVE_MICHAEL_SET_NOGC_H
33
34 #include <cds/intrusive/details/michael_set_base.h>
35 #include <cds/gc/nogc.h>
36 #include <cds/details/allocator.h>
37
38 namespace cds { namespace intrusive {
39
40     /// Michael's hash set (template specialization for gc::nogc)
41     /** @ingroup cds_intrusive_map
42         \anchor cds_intrusive_MichaelHashSet_nogc
43
44         This specialization is so-called append-only when no item
45         reclamation may be performed. The set does not support deleting of list item.
46
47         See \ref cds_intrusive_MichaelHashSet_hp "MichaelHashSet" for description of template parameters.
48         The template parameter \p OrderedList should be any \p cds::gc::nogc -derived ordered list, for example,
49         \ref cds_intrusive_MichaelList_nogc "append-only MichaelList".
50     */
51     template <
52         class OrderedList,
53 #ifdef CDS_DOXYGEN_INVOKED
54         class Traits = michael_set::traits
55 #else
56         class Traits
57 #endif
58     >
59     class MichaelHashSet< cds::gc::nogc, OrderedList, Traits >
60     {
61     public:
62         typedef cds::gc::nogc gc;        ///< Garbage collector
63         typedef OrderedList bucket_type; ///< Type of ordered list to be used as buckets
64         typedef Traits      traits;     ///< Set traits
65
66         typedef typename bucket_type::value_type     value_type;     ///< type of value to be stored in the set
67         typedef typename bucket_type::key_comparator key_comparator; ///< key comparing functor
68         typedef typename bucket_type::disposer       disposer;       ///< Node disposer functor
69
70         /// Hash functor for \p value_type and all its derivatives that you use
71         typedef typename cds::opt::v::hash_selector< typename traits::hash >::type hash;
72         typedef typename traits::item_counter item_counter; ///< Item counter type
73
74         /// Bucket table allocator
75         typedef cds::details::Allocator< bucket_type, typename traits::allocator > bucket_table_allocator;
76
77     protected:
78         item_counter    m_ItemCounter; ///< Item counter
79         hash            m_HashFunctor; ///< Hash functor
80         bucket_type *   m_Buckets;     ///< bucket table
81
82     private:
83         //@cond
84         const size_t    m_nHashBitmask;
85         //@endcond
86
87     protected:
88         //@cond
89         /// Calculates hash value of \p key
90         template <typename Q>
91         size_t hash_value( Q const & key ) const
92         {
93             return m_HashFunctor( key ) & m_nHashBitmask;
94         }
95
96         /// Returns the bucket (ordered list) for \p key
97         template <typename Q>
98         bucket_type&    bucket( Q const & key )
99         {
100             return m_Buckets[ hash_value( key ) ];
101         }
102         //@endcond
103
104     public:
105     ///@name Forward iterators
106     //@{
107         /// Forward iterator
108         /**
109             The forward iterator for Michael's set is based on \p OrderedList forward iterator and has some features:
110             - it has no post-increment operator
111             - it iterates items in unordered fashion
112
113             The iterator interface:
114             \code
115             class iterator {
116             public:
117                 // Default constructor
118                 iterator();
119
120                 // Copy construtor
121                 iterator( iterator const& src );
122
123                 // Dereference operator
124                 value_type * operator ->() const;
125
126                 // Dereference operator
127                 value_type& operator *() const;
128
129                 // Preincrement operator
130                 iterator& operator ++();
131
132                 // Assignment operator
133                 iterator& operator = (iterator const& src);
134
135                 // Equality operators
136                 bool operator ==(iterator const& i ) const;
137                 bool operator !=(iterator const& i ) const;
138             };
139             \endcode
140         */
141         typedef michael_set::details::iterator< bucket_type, false >    iterator;
142
143         /// Const forward iterator
144         /**
145             For iterator's features and requirements see \ref iterator
146         */
147         typedef michael_set::details::iterator< bucket_type, true >     const_iterator;
148
149         /// Returns a forward iterator addressing the first element in a set
150         /**
151             For empty set \code begin() == end() \endcode
152         */
153         iterator begin()
154         {
155             return iterator( m_Buckets[0].begin(), m_Buckets, m_Buckets + bucket_count() );
156         }
157
158         /// Returns an iterator that addresses the location succeeding the last element in a set
159         /**
160             Do not use the value returned by <tt>end</tt> function to access any item.
161             The returned value can be used only to control reaching the end of the set.
162             For empty set \code begin() == end() \endcode
163         */
164         iterator end()
165         {
166             return iterator( m_Buckets[bucket_count() - 1].end(), m_Buckets + bucket_count() - 1, m_Buckets + bucket_count() );
167         }
168
169         /// Returns a forward const iterator addressing the first element in a set
170         const_iterator begin() const
171         {
172             return cbegin();
173         }
174         /// Returns a forward const iterator addressing the first element in a set
175         const_iterator cbegin() const
176         {
177             return const_iterator( m_Buckets[0].cbegin(), m_Buckets, m_Buckets + bucket_count() );
178         }
179
180         /// Returns an const iterator that addresses the location succeeding the last element in a set
181         const_iterator end() const
182         {
183             return cend();
184         }
185         /// Returns an const iterator that addresses the location succeeding the last element in a set
186         const_iterator cend() const
187         {
188             return const_iterator( m_Buckets[bucket_count() - 1].cend(), m_Buckets + bucket_count() - 1, m_Buckets + bucket_count() );
189         }
190     //@}
191
192     public:
193         /// Initializes hash set
194         /**
195             The Michael's hash set is an unbounded container, but its hash table is non-expandable.
196             At construction time you should pass estimated maximum item count and a load factor.
197             The load factor is average size of one bucket - a small number between 1 and 10.
198             The bucket is an ordered single-linked list, searching in the bucket has linear complexity <tt>O(nLoadFactor)</tt>.
199             The constructor defines hash table size as rounding <tt>nMaxItemCount / nLoadFactor</tt> up to nearest power of two.
200         */
201         MichaelHashSet(
202             size_t nMaxItemCount,   ///< estimation of max item count in the hash set
203             size_t nLoadFactor      ///< load factor: estimation of max number of items in the bucket
204         ) : m_nHashBitmask( michael_set::details::init_hash_bitmask( nMaxItemCount, nLoadFactor ))
205         {
206             // GC and OrderedList::gc must be the same
207             static_assert( std::is_same<gc, typename bucket_type::gc>::value, "GC and OrderedList::gc must be the same");
208
209             // atomicity::empty_item_counter is not allowed as a item counter
210             static_assert( !std::is_same<item_counter, atomicity::empty_item_counter>::value,
211                            "atomicity::empty_item_counter is not allowed as a item counter");
212
213             m_Buckets = bucket_table_allocator().NewArray( bucket_count() );
214         }
215
216         /// Clears hash set object and destroys it
217         ~MichaelHashSet()
218         {
219             clear();
220             bucket_table_allocator().Delete( m_Buckets, bucket_count() );
221         }
222
223         /// Inserts new node
224         /**
225             The function inserts \p val in the set if it does not contain
226             an item with key equal to \p val.
227
228             Returns \p true if \p val is placed into the set, \p false otherwise.
229         */
230         bool insert( value_type& val )
231         {
232             bool bRet = bucket( val ).insert( val );
233             if ( bRet )
234                 ++m_ItemCounter;
235             return bRet;
236         }
237
238         /// Updates the element
239         /**
240             The operation performs inserting or changing data with lock-free manner.
241
242             If the item \p val not found in the set, then \p val is inserted iff \p bAllowInsert is \p true.
243             Otherwise, the functor \p func is called with item found.
244             The functor signature is:
245             \code
246                 struct functor {
247                     void operator()( bool bNew, value_type& item, value_type& val );
248                 };
249             \endcode
250             with arguments:
251             - \p bNew - \p true if the item has been inserted, \p false otherwise
252             - \p item - item of the set
253             - \p val - argument \p val passed into the \p %update() function
254             If new item has been inserted (i.e. \p bNew is \p true) then \p item and \p val arguments
255             refers to the same thing.
256
257             The functor may change non-key fields of the \p item.
258
259             Returns <tt> std::pair<bool, bool> </tt> where \p first is \p true if operation is successfull,
260             \p second is \p true if new item has been added or \p false if the item with \p key
261             already is in the set.
262
263             @warning For \ref cds_intrusive_MichaelList_hp "MichaelList" as the bucket see \ref cds_intrusive_item_creating "insert item troubleshooting".
264             \ref cds_intrusive_LazyList_hp "LazyList" provides exclusive access to inserted item and does not require any node-level
265             synchronization.
266         */
267         template <typename Func>
268         std::pair<bool, bool> update( value_type& val, Func func, bool bAllowInsert = true )
269         {
270             std::pair<bool, bool> bRet = bucket( val ).update( val, func, bAllowInsert );
271             if ( bRet.second )
272                 ++m_ItemCounter;
273             return bRet;
274         }
275         //@cond
276         template <typename Func>
277         CDS_DEPRECATED("ensure() is deprecated, use update()")
278         std::pair<bool, bool> ensure( value_type& val, Func func )
279         {
280             return update( val, func, true );
281         }
282         //@endcond
283
284         /// Checks whether the set contains \p key
285         /**
286
287             The function searches the item with key equal to \p key
288             and returns the pointer to an element found or \p nullptr.
289
290             Note the hash functor specified for class \p Traits template parameter
291             should accept a parameter of type \p Q that can be not the same as \p value_type.
292         */
293         template <typename Q>
294         value_type * contains( Q const& key )
295         {
296             return bucket( key ).contains( key );
297         }
298         //@cond
299         template <typename Q>
300         CDS_DEPRECATED("use contains()")
301         value_type * find( Q const& key )
302         {
303             return contains( key );
304         }
305         //@endcond
306
307         /// Checks whether the set contains \p key using \p pred predicate for searching
308         /**
309             The function is an analog of <tt>contains( key )</tt> but \p pred is used for key comparing.
310             \p Less functor has the interface like \p std::less.
311             \p Less must imply the same element order as the comparator used for building the set.
312         */
313         template <typename Q, typename Less>
314         value_type * contains( Q const& key, Less pred )
315         {
316             return bucket( key ).contains( key, pred );
317         }
318         //@cond
319         template <typename Q, typename Less>
320         CDS_DEPRECATED("use contains()")
321         value_type * find_with( Q const& key, Less pred )
322         {
323             return contains( key, pred );
324         }
325         //@endcond
326
327         /// Finds the key \p key
328         /** \anchor cds_intrusive_MichaelHashSet_nogc_find_func
329             The function searches the item with key equal to \p key and calls the functor \p f for item found.
330             The interface of \p Func functor is:
331             \code
332             struct functor {
333                 void operator()( value_type& item, Q& key );
334             };
335             \endcode
336             where \p item is the item found, \p key is the <tt>find</tt> function argument.
337
338             The functor can change non-key fields of \p item.
339             The functor does not serialize simultaneous access to the set \p item. If such access is
340             possible you must provide your own synchronization schema on item level to exclude unsafe item modifications.
341
342             The \p key argument is non-const since it can be used as \p f functor destination i.e., the functor
343             can modify both arguments.
344
345             Note the hash functor specified for class \p Traits template parameter
346             should accept a parameter of type \p Q that can be not the same as \p value_type.
347
348             The function returns \p true if \p key is found, \p false otherwise.
349         */
350         template <typename Q, typename Func>
351         bool find( Q& key, Func f )
352         {
353             return bucket( key ).find( key, f );
354         }
355         //@cond
356         template <typename Q, typename Func>
357         bool find( Q const& key, Func f )
358         {
359             return bucket( key ).find( key, f );
360         }
361         //@endcond
362
363         /// Finds the key \p key using \p pred predicate for searching
364         /**
365             The function is an analog of \ref cds_intrusive_MichaelHashSet_nogc_find_func "find(Q&, Func)"
366             but \p pred is used for key comparing.
367             \p Less functor has the interface like \p std::less.
368             \p pred must imply the same element order as the comparator used for building the set.
369         */
370         template <typename Q, typename Less, typename Func>
371         bool find_with( Q& key, Less pred, Func f )
372         {
373             return bucket( key ).find_with( key, pred, f );
374         }
375         //@cond
376         template <typename Q, typename Less, typename Func>
377         bool find_with( Q const& key, Less pred, Func f )
378         {
379             return bucket( key ).find_with( key, pred, f );
380         }
381         //@endcond
382
383         /// Clears the set (non-atomic)
384         /**
385             The function unlink all items from the set.
386             The function is not atomic. It cleans up each bucket and then resets the item counter to zero.
387             If there are a thread that performs insertion while \p %clear() is working the result is undefined in general case:
388             <tt> empty() </tt> may return \p true but the set may contain item(s).
389             Therefore, \p %clear() may be used only for debugging purposes.
390
391             For each item the \p disposer is called after unlinking.
392         */
393         void clear()
394         {
395             for ( size_t i = 0; i < bucket_count(); ++i )
396                 m_Buckets[i].clear();
397             m_ItemCounter.reset();
398         }
399
400
401         /// Checks if the set is empty
402         /**
403             Emptiness is checked by item counting: if item count is zero then the set is empty.
404             Thus, the correct item counting feature is an important part of Michael's set implementation.
405         */
406         bool empty() const
407         {
408             return size() == 0;
409         }
410
411         /// Returns item count in the set
412         size_t size() const
413         {
414             return m_ItemCounter;
415         }
416
417         /// Returns the size of hash table
418         /**
419             Since \p %MichaelHashSet cannot dynamically extend the hash table size,
420             the value returned is an constant depending on object initialization parameters;
421             see MichaelHashSet::MichaelHashSet for explanation.
422         */
423         size_t bucket_count() const
424         {
425             return m_nHashBitmask + 1;
426         }
427
428     };
429
430 }} // namespace cds::intrusive
431
432 #endif // #ifndef CDSLIB_INTRUSIVE_MICHAEL_SET_NOGC_H
433