dbcb369d24abf35f6cc5c9b4d87be915e426a4fc
[libcds.git] / cds / container / michael_set_nogc.h
1 //$$CDS-header$$
2
3 #ifndef CDSLIB_CONTAINER_MICHAEL_SET_NOGC_H
4 #define CDSLIB_CONTAINER_MICHAEL_SET_NOGC_H
5
6 #include <cds/container/details/michael_set_base.h>
7 #include <cds/gc/nogc.h>
8 #include <cds/details/allocator.h>
9
10 namespace cds { namespace container {
11
12     /// Michael's hash set (template specialization for gc::nogc)
13     /** @ingroup cds_nonintrusive_set
14         \anchor cds_nonintrusive_MichaelHashSet_nogc
15
16         This specialization is so-called append-only when no item
17         reclamation may be performed. The class does not support deleting of list item.
18
19         See \ref cds_nonintrusive_MichaelHashSet_hp "MichaelHashSet" for description of template parameters.
20         The template parameter \p OrderedList should be any \p gc::nogc -derived ordered list, for example,
21         \ref cds_nonintrusive_MichaelList_nogc "append-only MichaelList".
22     */
23     template <
24         class OrderedList,
25 #ifdef CDS_DOXYGEN_INVOKED
26         class Traits = michael_set::traits
27 #else
28         class Traits
29 #endif
30     >
31     class MichaelHashSet< cds::gc::nogc, OrderedList, Traits >
32     {
33     public:
34         typedef cds::gc::nogc gc;        ///< Garbage collector
35         typedef OrderedList bucket_type; ///< type of ordered list to be used as a bucket implementation
36         typedef Traits      traits;      ///< Set traits
37
38         typedef typename bucket_type::value_type        value_type;     ///< type of value stored in the list
39         typedef typename bucket_type::key_comparator    key_comparator; ///< key comparison functor
40
41         /// Hash functor for \ref value_type and all its derivatives that you use
42         typedef typename cds::opt::v::hash_selector< typename traits::hash >::type hash;
43         typedef typename traits::item_counter  item_counter; ///< Item counter type
44
45         /// Bucket table allocator
46         typedef cds::details::Allocator< bucket_type, typename traits::allocator >  bucket_table_allocator;
47
48         //@cond
49         typedef cds::container::michael_set::implementation_tag implementation_tag;
50         //@endcond
51
52     protected:
53         //@cond
54         typedef typename bucket_type::iterator        bucket_iterator;
55         typedef typename bucket_type::const_iterator  bucket_const_iterator;
56         //@endcond
57
58     protected:
59         item_counter    m_ItemCounter;   ///< Item counter
60         hash            m_HashFunctor;   ///< Hash functor
61         bucket_type *   m_Buckets;       ///< bucket table
62
63     private:
64         //@cond
65         const size_t    m_nHashBitmask;
66         //@endcond
67
68     protected:
69         //@cond
70         /// Calculates hash value of \p key
71         template <typename Q>
72         size_t hash_value( const Q& key ) const
73         {
74             return m_HashFunctor( key ) & m_nHashBitmask;
75         }
76
77         /// Returns the bucket (ordered list) for \p key
78         template <typename Q>
79         bucket_type&    bucket( const Q& key )
80         {
81             return m_Buckets[ hash_value( key ) ];
82         }
83         //@endcond
84
85     public:
86         /// Forward iterator
87         /**
88             The forward iterator for Michael's set is based on \p OrderedList forward iterator and has some features:
89             - it has no post-increment operator
90             - it iterates items in unordered fashion
91         */
92         typedef michael_set::details::iterator< bucket_type, false >    iterator;
93
94         /// Const forward iterator
95         /**
96             For iterator's features and requirements see \ref iterator
97         */
98         typedef michael_set::details::iterator< bucket_type, true >     const_iterator;
99
100         /// Returns a forward iterator addressing the first element in a set
101         /**
102             For empty set \code begin() == end() \endcode
103         */
104         iterator begin()
105         {
106             return iterator( m_Buckets[0].begin(), m_Buckets, m_Buckets + bucket_count() );
107         }
108
109         /// Returns an iterator that addresses the location succeeding the last element in a set
110         /**
111             Do not use the value returned by <tt>end</tt> function to access any item.
112             The returned value can be used only to control reaching the end of the set.
113             For empty set \code begin() == end() \endcode
114         */
115         iterator end()
116         {
117             return iterator( m_Buckets[bucket_count() - 1].end(), m_Buckets + bucket_count() - 1, m_Buckets + bucket_count() );
118         }
119
120         /// Returns a forward const iterator addressing the first element in a set
121         //@{
122         const_iterator begin() const
123         {
124             return get_const_begin();
125         }
126         const_iterator cbegin() const
127         {
128             return get_const_begin();
129         }
130         //@}
131
132         /// Returns an const iterator that addresses the location succeeding the last element in a set
133         //@{
134         const_iterator end() const
135         {
136             return get_const_end();
137         }
138         const_iterator cend() const
139         {
140             return get_const_end();
141         }
142         //@}
143
144     private:
145         //@cond
146         const_iterator get_const_begin() const
147         {
148             return const_iterator( const_cast<bucket_type const&>(m_Buckets[0]).begin(), m_Buckets, m_Buckets + bucket_count() );
149         }
150         const_iterator get_const_end() const
151         {
152             return const_iterator( const_cast<bucket_type const&>(m_Buckets[bucket_count() - 1]).end(), m_Buckets + bucket_count() - 1, m_Buckets + bucket_count() );
153         }
154         //@endcond
155
156     public:
157         /// Initialize hash set
158         /**
159             The Michael's hash set is non-expandable container. You should point the average count of items \p nMaxItemCount
160             when you create an object.
161             \p nLoadFactor parameter defines average count of items per bucket and it should be small number between 1 and 10.
162             Remember, since the bucket implementation is an ordered list, searching in the bucket is linear [<tt>O(nLoadFactor)</tt>].
163
164             The ctor defines hash table size as rounding <tt>nMaxItemCount / nLoadFactor</tt> up to nearest power of two.
165         */
166         MichaelHashSet(
167             size_t nMaxItemCount,   ///< estimation of max item count in the hash set
168             size_t nLoadFactor      ///< load factor: estimation of max number of items in the bucket
169         ) : m_nHashBitmask( michael_set::details::init_hash_bitmask( nMaxItemCount, nLoadFactor ))
170         {
171             // GC and OrderedList::gc must be the same
172             static_assert( std::is_same<gc, typename bucket_type::gc>::value, "GC and OrderedList::gc must be the same");
173
174             // atomicity::empty_item_counter is not allowed as a item counter
175             static_assert( !std::is_same<item_counter, atomicity::empty_item_counter>::value,
176                            "cds::atomicity::empty_item_counter is not allowed as a item counter");
177
178             m_Buckets = bucket_table_allocator().NewArray( bucket_count() );
179         }
180
181         /// Clears hash set and destroys it
182         ~MichaelHashSet()
183         {
184             clear();
185             bucket_table_allocator().Delete( m_Buckets, bucket_count() );
186         }
187
188         /// Inserts new node
189         /**
190             The function inserts \p val in the set if it does not contain
191             an item with key equal to \p val.
192
193             Return an iterator pointing to inserted item if success, otherwise \ref end()
194         */
195         template <typename Q>
196         iterator insert( const Q& val )
197         {
198             bucket_type& refBucket = bucket( val );
199             bucket_iterator it = refBucket.insert( val );
200
201             if ( it != refBucket.end() ) {
202                 ++m_ItemCounter;
203                 return iterator( it, &refBucket, m_Buckets + bucket_count() );
204             }
205
206             return end();
207         }
208
209         /// Inserts data of type \ref value_type constructed with <tt>std::forward<Args>(args)...</tt>
210         /**
211             Return an iterator pointing to inserted item if success \ref end() otherwise
212         */
213         template <typename... Args>
214         iterator emplace( Args&&... args )
215         {
216             bucket_type& refBucket = bucket( value_type(std::forward<Args>(args)...));
217             bucket_iterator it = refBucket.emplace( std::forward<Args>(args)... );
218
219             if ( it != refBucket.end() ) {
220                 ++m_ItemCounter;
221                 return iterator( it, &refBucket, m_Buckets + bucket_count() );
222             }
223
224             return end();
225         }
226
227         /// Updates the element
228         /**
229             The operation performs inserting or changing data with lock-free manner.
230
231             If the item \p val not found in the set, then \p val is inserted iff \p bAllowInsert is \p true.
232
233             Returns <tt> std::pair<iterator, bool> </tt> where \p first is an iterator pointing to
234             item found or inserted, or \p end() if \p bAllowInsert is \p false, 
235             \p second is true if new item has been added or \p false if the item is already in the set.
236
237             @warning For \ref cds_intrusive_MichaelList_hp "MichaelList" as the bucket see \ref cds_intrusive_item_creating "insert item troubleshooting".
238             \ref cds_intrusive_LazyList_hp "LazyList" provides exclusive access to inserted item and does not require any node-level
239             synchronization.
240         */
241         template <typename Q>
242         std::pair<iterator, bool> update( Q const& val, bool bAllowInsert = true )
243         {
244             bucket_type& refBucket = bucket( val );
245             std::pair<bucket_iterator, bool> ret = refBucket.update( val, bAllowInsert );
246
247             if ( ret.first != refBucket.end() ) {
248                 if ( ret.second )
249                     ++m_ItemCounter;
250                 return std::make_pair( iterator( ret.first, &refBucket, m_Buckets + bucket_count() ), ret.second );
251             }
252             return std::make_pair( end(), ret.second );
253         }
254         //@cond
255         template <typename Q>
256         CDS_DEPRECATED("ensure() is deprecated, use update()")
257         std::pair<iterator, bool> ensure( Q const& val )
258         {
259             return update( val, true );
260         }
261         //@endcond
262
263         /// Checks whether the set contains \p key
264         /**
265             The function searches the item with key equal to \p key
266             and returns an iterator pointed to item found if the key is found,
267             or \ref end() otherwise.
268
269             Note the hash functor specified for class \p Traits template parameter
270             should accept a parameter of type \p Q that can be not the same as \p value_type.
271         */
272         template <typename Q>
273         iterator contains( Q const& key )
274         {
275             bucket_type& refBucket = bucket( key );
276             bucket_iterator it = refBucket.contains( key );
277             if ( it != refBucket.end() )
278                 return iterator( it, &refBucket, m_Buckets + bucket_count() );
279
280             return end();
281         }
282         //@cond
283         template <typename Q>
284         CDS_DEPRECATED("use contains()")
285         iterator find( Q const& key )
286         {
287             return contains( key );
288         }
289         //@endcond
290
291         /// Checks whether the set contains \p key using \p pred predicate for searching
292         /**
293             The function is an analog of <tt>contains( key )</tt> but \p pred is used for key comparing.
294             \p Less functor has the interface like \p std::less.
295             \p Less must imply the same element order as the comparator used for building the set.
296         */
297         template <typename Q, typename Less>
298         iterator contains( Q const& key, Less pred )
299         {
300             bucket_type& refBucket = bucket( key );
301             bucket_iterator it = refBucket.contains( key, pred );
302             if ( it != refBucket.end() )
303                 return iterator( it, &refBucket, m_Buckets + bucket_count() );
304
305             return end();
306         }
307         //@cond
308         template <typename Q, typename Less>
309         CDS_DEPRECATED("use contains()")
310         iterator find_with( Q const& key, Less pred )
311         {
312             return contains( key, pred );
313         }
314         //@endcond
315
316         /// Clears the set (not atomic)
317         void clear()
318         {
319             for ( size_t i = 0; i < bucket_count(); ++i )
320                 m_Buckets[i].clear();
321             m_ItemCounter.reset();
322         }
323
324         /// Checks if the set is empty
325         /**
326             The emptiness is checked by the item counting: if item count is zero then the set is empty.
327             Thus, the correct item counting feature is an important part of Michael's set implementation.
328         */
329         bool empty() const
330         {
331             return size() == 0;
332         }
333
334         /// Returns item count in the set
335         size_t size() const
336         {
337             return m_ItemCounter;
338         }
339
340         /// Returns the size of hash table
341         /**
342             Since \p %MichaelHashSet cannot dynamically extend the hash table size,
343             the value returned is an constant depending on object initialization parameters;
344             see MichaelHashSet::MichaelHashSet for explanation.
345         */
346         size_t bucket_count() const
347         {
348             return m_nHashBitmask + 1;
349         }
350     };
351
352 }} // cds::container
353
354 #endif // ifndef CDSLIB_CONTAINER_MICHAEL_SET_NOGC_H