Major merge from 'dev'
[libcds.git] / cds / opt / options.h
1 //$$CDS-header$$
2
3 #ifndef CDSLIB_OPT_OPTIONS_H
4 #define CDSLIB_OPT_OPTIONS_H
5
6 /*
7     Framework to define template options
8
9     Editions:
10         2011.01.23 khizmax  Created
11 */
12
13 #include <cds/details/aligned_type.h>
14 #include <cds/user_setup/allocator.h>
15 #include <cds/user_setup/cache_line.h>
16 #include <cds/algo/atomic.h>
17 #include <stdlib.h> // rand, srand
18
19 namespace cds {
20
21 /// Framework to define template options
22 /**
23     There are two kind of options:
24     - \p type-option - option that determines a data type. The template argument \p Type of the option is a type.
25     - \p value-option - option that determines a value. The template argument \p Value of the option is a value.
26 */
27 namespace opt {
28
29     /// Predefined options value (generally, for the options that determine the data types)
30     namespace v {}
31
32     /// Type indicates that an option is not specified and the default one should be used
33     struct none
34     {
35         //@cond
36         template <class Base> struct pack: public Base
37         {};
38         //@endcond
39     };
40
41     /// Metafunction for selecting default option value
42     /**
43         Template parameters:
44         - \p Option - option value
45         - \p Default - default option value
46         - \p Value - option value if \p Option is not opt::none
47
48         If \p Option is opt::none, the metafunction result is \p Default, otherwise
49         the result is \p Value.
50
51         Examples:
52         \code
53         // default_spin is cds::sync::spin
54         typedef typename cds::opt::select_default< cds::opt::none, cds::sync::spin >::type  default_spin;
55
56         // spin_32bit is cds::sync::reentrant_spin32
57         typedef typename cds::opt::select_default< cds::opt::none, cds::sync::reentrant_spin32 >::type  spin_32bit;
58         \endcode
59     */
60     template <typename Option, typename Default, typename Value = Option>
61     struct select_default
62     {
63         typedef Value type ;   ///< metafunction result
64     };
65     //@cond
66     template <typename Default>
67     struct select_default< none, Default >
68     {
69         typedef Default type;
70     };
71     //@endcond
72
73     /// Metafunction to select option value
74     /**
75         This metafunction is intended for extracting the value of the \p Option option.
76         For example,
77         \code
78         #include <cds/opt/options.h>
79         #include <type_traits> // only for testing purpose (static_assert)
80
81         struct tag_a;
82
83         // Define option
84         typedef cds::opt::tag< tag_a >  tag_option;
85
86         // What is the value of the tag_option?
87         // How we can extract tag_a from tag_option?
88         // Here is a solution:
89         typedef cds::opt::value< tag_option >::tag  tag_option_value;
90
91         // tag_option_value is the same as tag_a
92         static_assert( std::is_same< tag_option_value, tag_a >::value, "Error: tag_option_value != tag_a" );
93
94         \endcode
95     */
96     template <typename Option>
97     struct value: public Option::template pack<none>
98     {};
99
100
101     /// [type-option] Option setter specifies a tag
102     /**
103         Suppose, you have a struct
104         \code
105         struct Feature
106         {  .... };
107         \endcode
108         and you want that your class \p X would be derived from several \p Feature:
109         \code
110             class X: public Feature, public Feature
111             { .... };
112         \endcode
113
114         How can you distinguish one \p Feature from another?
115         You may use a tag option:
116         \code
117             template <typename Tag>
118             struct Feature
119             { .... };
120
121             class tag_a;
122             class tag_b;
123             class X: public Feature< tag_a >, public Feature< tag_b >
124             { .... };
125         \endcode
126         Now you can distinguish one \p Feature from another:
127         \code
128             X x;
129             Feature<tag_a>& fa = static_cast< Feature<tag_a> >( x );
130             Feature<tag_b>& fb = static_cast< Feature<tag_b> >( x );
131         \endcode
132
133         \p tag option setter allows you to do things like this for an option-centric approach:
134         \code
135         template <typename ...Options>
136         struct Feature
137         { .... };
138
139         class tag_a;
140         class tag_b;
141         class X: public Feature< tag<tag_a> >, public Feature< tag<tag_b> >
142         { .... };
143         \endcode
144
145         This option setter is widely used in cds::intrusive containers to distinguish
146         between different intrusive part of container's node.
147
148         An incomplete type can serve as a \p Tag.
149     */
150     template <typename Tag>
151     struct tag {
152         //@cond
153         template<class Base> struct pack: public Base
154         {
155             typedef Tag tag;
156         };
157         //@endcond
158     };
159
160     /// [type-option] Option setter specifies lock class
161     /**
162         Specification of the \p Type class is:
163         \code
164         struct Lock {
165             void lock();
166             void unlock();
167         };
168         \endcode
169     */
170     template <typename Type>
171     struct lock_type {
172         //@cond
173         template<class Base> struct pack: public Base
174         {
175             typedef Type lock_type;
176         };
177         //@endcond
178     };
179
180     /// [type-option] @ref cds_sync_monitor "Monitor" type setter
181     /**
182         This option setter specifyes @ref cds_sync_monitor "synchronization monitor"
183         for blocking container.
184     */
185     template <typename Type>
186     struct sync_monitor {
187         //@cond
188         template <class Base> struct pack : public Base
189         {
190             typedef Type sync_monitor;
191         };
192         //@endcond
193     };
194
195     /// [type-option] Back-off strategy option setter
196     /**
197         Back-off strategy used in some algorithm.
198         See cds::backoff namespace for back-off explanation and supported interface.
199     */
200     template <typename Type>
201     struct back_off {
202         //@cond
203         template <class Base> struct pack: public Base
204         {
205             typedef Type back_off;
206         };
207         //@endcond
208     };
209
210     /// [type-option] Option setter for garbage collecting schema used
211     /**
212         Possible values of \p GC template parameter are:
213         - cds::gc::HP - Hazard Pointer garbage collector
214         - cds::gc::DHP - Dynamic Hazard Pointer garbage collector
215         - cds::gc::none::GC - No garbage collector (not supported for some containers)
216     */
217     template <typename GC>
218     struct gc {
219         //@cond
220         template <class Base> struct pack: public Base
221         {
222             typedef GC gc;
223         };
224         //@endcond
225     };
226
227     /// [type-option] Option setter for an allocator
228     /**
229         \p Type is allocator with \p std::allocator interface. Default is value of macro CDS_DEFAULT_ALLOCATOR
230         that, in turn, is \p std::allocator.
231
232         The \p libcds containers actively use rebinding to convert an allocator of one type to another. Thus,
233         you may specify any valid type as std::allocator's template parameter.
234
235         See also opt::node_allocator
236     */
237     template <typename Type>
238     struct allocator {
239         //@cond
240         template <typename Base> struct pack: public Base
241         {
242             typedef Type allocator;
243         };
244         //@endcond
245     };
246
247     /// [type-option] Option setter for node allocator
248     /**
249         \p Type is allocator with \p std::allocator interface. Default is value of macro CDS_DEFAULT_ALLOCATOR
250         that, in turn, is \p std::allocator.
251
252         Many node-base containers require an allocator for maintaining data (container's node) and for internal use.
253         Sometimes, this types of allocator should be different for performance reason.
254         For example, we should like to allocate the node from a pool of preallocated nodes.
255         Such pool can be seen as the node allocator.
256
257         Usually, if a container supports \p opt::allocator and \p %opt::node_allocator options
258         and \p opt::node_allocator is not specified the \p %opt::allocator option is used for maintaining the nodes.
259
260         The \p libcds containers actively use rebinding to convert an allocator of one type to another. Thus,
261         you may specify any valid type as std::allocator's template parameter.
262     */
263     template <typename Type>
264     struct node_allocator {
265         //@cond
266             template <typename Base> struct pack: public Base
267             {
268                 typedef Type node_allocator;
269             };
270         //@endcond
271     };
272
273     /// [type-option] Option setter for item counting
274     /**
275         Some data structure (for example, queues) has additional feature for item counting.
276         This option allows to set up appropriate item counting policy for that data structure.
277
278         Predefined option \p Type:
279         - atomicity::empty_item_counter - no item counting performed. It is default policy for many
280             containers
281         - atomicity::item_counter - the class that provides atomically item counting
282         - opt::v::sequential_item_counter - simple non-atomic item counter. This item counter is not intended for
283             concurrent containers and may be used only if it is explicitly noted.
284
285         You may provide other implementation of atomicity::item_counter interface for your needs.
286
287         Note, the item counting in lock-free containers cannot be exact; for example, if
288         item counter for a container returns zero it is not mean that the container is empty.
289         Thus, item counter may be used for statistical purposes only.
290     */
291     template <typename Type>
292     struct item_counter {
293         //@cond
294         template <typename Base> struct pack: public Base
295         {
296             typedef Type item_counter;
297         };
298         //@endcond
299     };
300
301     namespace v {
302         /// Sequential non-atomic item counter
303         /**
304             This type of item counter is not intended for concurrent containers
305             and may be used only if it is explicitly noted.
306         */
307         class sequential_item_counter
308         {
309         public:
310             typedef size_t counter_type    ;  ///< Counter type
311         protected:
312             counter_type  m_nCounter ;      ///< Counter
313
314         public:
315             sequential_item_counter()
316                 : m_nCounter(0)
317             {}
318
319             /// Returns current value of the counter
320             counter_type    value() const
321             {
322                 return m_nCounter;
323             }
324
325             /// Same as \ref value() with relaxed memory ordering
326             operator counter_type() const
327             {
328                 return value();
329             }
330
331             /// Increments the counter. Semantics: postincrement
332             counter_type inc()
333             {
334                 return m_nCounter++;
335             }
336
337             /// Decrements the counter. Semantics: postdecrement
338             counter_type dec()
339             {
340                 return m_nCounter--;
341             }
342
343             /// Preincrement
344             counter_type operator ++()
345             {
346                 return inc() + 1;
347             }
348             /// Postincrement
349             counter_type operator ++(int)
350             {
351                 return inc();
352             }
353
354             /// Predecrement
355             counter_type operator --()
356             {
357                 return dec() - 1;
358             }
359             /// Postdecrement
360             counter_type operator --(int)
361             {
362                 return dec();
363             }
364
365             /// Resets count to 0
366             void reset()
367             {
368                 m_nCounter = 0;
369             }
370         };
371     } // namespace v
372
373     /// Special alignment constants for \ref cds::opt::alignment option
374     enum special_alignment {
375         no_special_alignment = 0,   ///< no special alignment
376         cache_line_alignment = 1    ///< use cache line size defined in cds/user_setup/cache_line.h
377     };
378
379     /// [value-option] Alignment option setter
380     /**
381         Alignment for some internal data of containers. May be useful to solve false sharing problem.
382         \p Value defines desired alignment and it may be power of two integer or predefined values from
383         \ref special_alignment enum.
384     */
385     template <unsigned int Value>
386     struct alignment {
387         //@cond
388         template <typename Base> struct pack: public Base
389         {
390             enum { alignment = Value };
391         };
392         //@endcond
393     };
394
395     //@cond
396     namespace details {
397         template <typename Type, unsigned int Alignment>
398         struct alignment_setter {
399             typedef typename cds::details::aligned_type< Type, Alignment >::type  type;
400         };
401
402         template <typename Type>
403         struct alignment_setter<Type, no_special_alignment> {
404             typedef Type type;
405         };
406
407         template <typename Type>
408         struct alignment_setter<Type, cache_line_alignment> {
409             typedef typename cds::details::aligned_type< Type, c_nCacheLineSize >::type  type;
410         };
411
412     } // namespace details
413     //@endcond
414
415     /// Special padding constants for \p cds::opt::padding option
416     enum special_padding {
417         no_special_padding = 0,   ///< no special padding
418         cache_line_padding = 1,   ///< use cache line size defined in cds/user_setup/cache_line.h
419
420         /// Apply padding only for tiny data of size less than required padding
421         /**
422             The flag means that if your data size is less than the casheline size, the padding is applyed.
423             Otherwise no padding will be applyed.
424
425             This flag is applyed for padding value:
426             \code
427             cds::opt::padding< cds::opt::cache_line_padding | cds::opt::padding_tiny_data_only >;
428             cds::opt::padding< 256 | cds::opt::padding_tiny_data_only >;
429             \endcode
430         */
431         padding_tiny_data_only = 0x80000000,
432
433         //@cond
434         padding_flags = padding_tiny_data_only
435         //@endcond
436     };
437
438     /// [value-option] Padding option setter
439     /**
440         The padding for the internal data of some containers. May be useful to solve false sharing problem.
441         \p Value defines desired padding and it may be power of two integer or predefined values from
442         \p special_padding enum.
443     */
444     template <unsigned int Value>
445     struct padding {
446         //@cond
447         template <typename Base> struct pack: public Base
448         {
449             enum { padding = Value };
450         };
451         //@endcond
452     };
453
454     //@cond
455     namespace details {
456         enum padding_vs_datasize {
457             padding_datasize_less,
458             padding_datasize_equal,
459             padding_datasize_greater
460         };
461
462         template < typename T, unsigned int Padding, bool NoPadding, padding_vs_datasize Relation, bool TinyOnly >
463         struct apply_padding_helper;
464
465         template <typename T, padding_vs_datasize Relation, bool TinyOnly >
466         struct apply_padding_helper < T, 0, true, Relation, TinyOnly >
467         {
468             struct type {
469                 T   data;
470             };
471         };
472
473         template <typename T, unsigned int Padding, bool TinyOnly >
474         struct apply_padding_helper < T, Padding, false, padding_datasize_equal, TinyOnly >
475         {
476             struct type {
477                 T   data;
478             };
479         };
480
481         template <typename T, unsigned int Padding, bool TinyOnly >
482         struct apply_padding_helper < T, Padding, false, padding_datasize_less, TinyOnly >
483         {
484             struct type {
485                 T data;
486                 uint8_t pad_[Padding - sizeof( T )];
487             };
488         };
489
490         template <typename T, unsigned int Padding >
491         struct apply_padding_helper < T, Padding, false, padding_datasize_greater, false >
492         {
493             struct type {
494                 T data;
495                 uint8_t pad_[Padding - sizeof( T ) % Padding];
496             };
497         };
498
499         template <typename T, unsigned int Padding >
500         struct apply_padding_helper < T, Padding, false, padding_datasize_greater, true >
501         {
502             struct type {
503                 T data;
504             };
505         };
506
507         template <typename T, unsigned int Padding >
508         struct apply_padding
509         {
510         private:
511             enum { padding = Padding & ~padding_flags };
512
513         public:
514             static CDS_CONSTEXPR const size_t c_nPadding =
515                 static_cast<unsigned int>(padding) == static_cast<unsigned int>(cache_line_padding) ? cds::c_nCacheLineSize :
516                 static_cast<unsigned int>(padding) == static_cast<unsigned int>(no_special_padding) ? 0 : padding;
517
518             static_assert( (c_nPadding & (c_nPadding - 1)) == 0, "Padding must be a power-of-two number" );
519
520             typedef typename apply_padding_helper< T,
521                 c_nPadding,
522                 c_nPadding == 0,
523                 sizeof( T ) < c_nPadding ? padding_datasize_less : sizeof( T ) == c_nPadding ? padding_datasize_equal : padding_datasize_greater,
524                 (Padding & padding_tiny_data_only) != 0
525             >::type type;
526         };
527
528     } // namespace details
529     //@endcond
530
531
532     /// [type-option] Generic option setter for statisitcs
533     /**
534         This option sets a type to gather statistics.
535         The option is generic - no predefined type(s) is provided.
536         The particular \p Type of statistics depends on internal structure of the object.
537     */
538     template <typename Type>
539     struct stat {
540         //@cond
541         template <typename Base> struct pack: public Base
542         {
543             typedef Type stat;
544         };
545         //@endcond
546     };
547
548     /// [type-option] Option setter for C++ memory model
549     /**
550         The <b>cds</b> library supports following memory ordering constraints for atomic operations in container implementation:
551         - v::relaxed_ordering - relaxed C++ memory model. This mode supports full set of memory ordering constraints:
552             \p memory_order_relaxed, \p memory_order_acquire, \p memory_order_release and so on.
553         - v::sequential_consistent - sequentially consistent C++ memory model (default memory ordering for C++). In
554             this mode any memory ordering constraint maps to \p memory_order_seq_cst.
555
556         The \p Type template parameter can be v::relaxed_ordering or v::sequential_consistent.
557
558         You may mix different memory ordering options for different containers: one declare as sequentially consistent,
559         another declare as relaxed.
560         Usually, v::relaxed_ordering is the default memory ordering for <b>cds</b> containers.
561     */
562     template <typename Type>
563     struct memory_model {
564         //@cond
565         template <typename Base> struct pack: public Base
566         {
567             typedef Type memory_model;
568         };
569         //@endcond
570     };
571
572     namespace v {
573         /// Relaxed memory ordering model
574         /**
575             In this memory model the memory constraints are defined according to C++ Memory Model specification.
576
577             See opt::memory_model for explanations
578         */
579         struct relaxed_ordering {
580             //@cond
581
582             // For new C++11 (cds-1.1.0)
583             static const atomics::memory_order memory_order_relaxed    = atomics::memory_order_relaxed;
584             static const atomics::memory_order memory_order_consume    = atomics::memory_order_consume;
585             static const atomics::memory_order memory_order_acquire    = atomics::memory_order_acquire;
586             static const atomics::memory_order memory_order_release    = atomics::memory_order_release;
587             static const atomics::memory_order memory_order_acq_rel    = atomics::memory_order_acq_rel;
588             static const atomics::memory_order memory_order_seq_cst    = atomics::memory_order_seq_cst;
589             //@endcond
590         };
591
592         /// Sequential consistent memory ordering model
593         /**
594             In this memory model any memory constraint is equivalent to \p memory_order_seq_cst.
595
596             See opt::memory_model for explanations
597         */
598         struct sequential_consistent {
599             //@cond
600
601             // For new C++11 (cds-1.1.0)
602             static const atomics::memory_order memory_order_relaxed    = atomics::memory_order_seq_cst;
603             static const atomics::memory_order memory_order_consume    = atomics::memory_order_seq_cst;
604             static const atomics::memory_order memory_order_acquire    = atomics::memory_order_seq_cst;
605             static const atomics::memory_order memory_order_release    = atomics::memory_order_seq_cst;
606             static const atomics::memory_order memory_order_acq_rel    = atomics::memory_order_seq_cst;
607             static const atomics::memory_order memory_order_seq_cst    = atomics::memory_order_seq_cst;
608             //@endcond
609         };
610     } // namespace v
611
612     /// [type-option] Base type traits option setter
613     /**
614         This option setter is intended generally for internal use for type rebinding.
615     */
616     template <typename Type>
617     struct type_traits {
618         //@cond
619         template <typename Base> struct pack: public Base
620         {
621             typedef Type type_traits;
622         };
623         //@endcond
624     };
625
626     /// Resizing policy option
627     /**
628         This option specifies the resizing policy that decides when to resize a container.
629         Used in some containers, for example, in container::StripedHashSet, intrusive::StripedHashSet.
630
631         The real resizing policy specified by \p Type does strongly depend on a container
632         that supports this option, see container documentation about possibly \p Type values.
633     */
634     template <typename Type>
635     struct resizing_policy {
636         //@cond
637         template <typename Base> struct pack: public Base
638         {
639             typedef Type resizing_policy;
640         };
641         //@endcond
642     };
643
644     /// Copy policy option
645     /**
646         The copy policy defines an item copying algorithm which is used, for example, when a container is resized.
647         It is very specific algorithm depending on type of the container.
648     */
649     template <typename Type>
650     struct copy_policy {
651         //@cond
652         template <typename Base> struct pack: public Base
653         {
654             typedef Type copy_policy;
655         };
656         //@endcond
657     };
658
659     /// Swap policy option
660     /**
661         The swap policy specifies an algorithm for swapping two objects.
662         Usually, the default policy is \p std::swap (see opt::v::default_swap_policy):
663
664         @code
665         struct std_swap {
666             template <typename T>
667             void operator ()( T& v1, T& v2 )
668             {
669                 std::swap( v1, v2 );
670             }
671         };
672         @endcode
673     */
674     template <typename Type>
675     struct swap_policy {
676         //@cond
677         template <typename Base> struct pack: public Base
678         {
679             typedef Type swap_policy;
680         };
681         //@endcond
682     };
683
684     namespace v {
685
686         /// Default swap policy (see opt::swap_policy option)
687         /**
688             The default swap policy is wrappr around \p std::swap algorithm.
689         */
690         struct default_swap_policy {
691             /// Performs swapping of \p v1 and \p v2 using \p std::swap algo
692             template <typename T>
693             void operator()( T& v1, T& v2 ) const
694             {
695                 std::swap( v1, v2 );
696             }
697         };
698     } // namespace v
699
700     /// Move policy option
701     /**
702         The move policy specifies an algorithm for moving object content.
703         In trivial case, it can be simple assignment.
704
705         The move interface is:
706         \code
707         template <typename T>
708         struct move_policy {
709             void operator()( T& dest, T& src );
710         };
711         \endcode
712
713         Note that in move algorithm the \p src source argument can be changed too.
714         So you can use move semantics.
715
716         Usually, the default move policy is opt::v::assignment_move_policy
717     */
718     template <typename Type>
719     struct move_policy {
720         //@cond
721         template <typename Base> struct pack: public Base
722         {
723             typedef Type move_policy;
724         };
725         //@endcond
726     };
727
728     namespace v {
729         /// \ref opt::move_policy "Move policy" based on assignment operator
730         struct assignment_move_policy
731         {
732             /// <tt> dest = src </tt>
733             template <typename T>
734             void operator()( T& dest, T const& src ) const
735             {
736                 dest = src;
737             }
738         };
739     } // namespace v
740
741     /// [value-option] Enable sorting
742     /**
743         This option enables (<tt>Enable = true</tt>) or disables (<tt>Enable == false</tt>)
744         sorting of a container.
745     */
746     template <bool Enable>
747     struct sort {
748         //@cond
749         template <typename Base> struct pack: public Base
750         {
751             static bool const sort = Enable;
752         };
753         //@endcond
754     };
755
756     /// [type-option] Concurrent access policy
757     /**
758         This option specifies synchronization strategy for fine-grained lock-based containers.
759         The option has no predefined \p Policy type.
760         For each container that accepts this option the range of available \p Policy types
761         is unique.
762     */
763     template <typename Policy>
764     struct mutex_policy {
765         //@cond
766         template <typename Base> struct pack: public Base
767         {
768             typedef Policy mutex_policy;
769         };
770         //@endcond
771     };
772
773
774     /// [type-option] Random number generator
775     /**
776         The option specifies a random number generator.
777         \p Random can be any STL random number generator producing
778         unsigned integer: \p std::linear_congruential_engine,
779         \p std::mersenne_twister_engine, \p std::subtract_with_carry_engine
780         and so on, or opt::v::c_rand.
781
782     */
783     template <typename Random>
784     struct random_engine {
785         //@cond
786         template <typename Base> struct pack: public Base
787         {
788             typedef Random random_engine;
789         };
790         //@endcond
791     };
792
793     namespace v {
794         /// \p rand() -base random number generator
795         /**
796             This generator returns a pseudorandom integer in the range 0 to \p RAND_MAX (32767).
797         */
798         struct c_rand {
799             typedef unsigned int result_type; ///< Result type
800
801             /// Constructor initializes object calling \p srand()
802             c_rand()
803             {
804                 srand(1);
805             }
806
807             /// Returns next random number calling \p rand()
808             result_type operator()()
809             {
810                 return (result_type) rand();
811             }
812         };
813     } // namespace v
814
815     //@cond
816     // For internal use
817     template <typename Accessor>
818     struct key_accessor {
819         template <typename Base> struct pack: public Base
820         {
821             typedef Accessor key_accessor;
822         };
823     };
824
825     template <typename Traits, typename ReplaceWith, typename WhatReplace = none >
826     struct replace_key_accessor {
827         typedef typename std::conditional<
828             std::is_same< typename Traits::key_accessor, WhatReplace >::value,
829             typename opt::key_accessor< ReplaceWith >::template pack< Traits >,
830             Traits
831         >::type type;
832     };
833     //@endcond
834
835 }}  // namespace cds::opt
836
837 #include <cds/opt/make_options_var.h>
838
839 #endif  // #ifndef CDSLIB_OPT_OPTIONS_H