-
Notifications
You must be signed in to change notification settings - Fork 0
/
brick-types
1727 lines (1387 loc) · 50.5 KB
/
brick-types
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// -*- mode: C++; indent-tabs-mode: nil; c-basic-offset: 4 -*-
/*
* Assorted types, mostly for C++11.
* - Maybe a = Just a | Nothing (w/ a limited variant for C++98)
* - Unit: single-valued type (empty structure)
* - Union: discriminated (tagged) union
* - StrongEnumFlags
* - type-traits: is_detected
*/
/*
* (c) 2006, 2014 Petr Ročkai <[email protected]>
* (c) 2013-2015 Vladimír Štill <[email protected]>
* (c) 2018 Henrich Lauko <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#pragma once
#include "brick-assert"
#include "brick-string"
#include <memory>
#include <cstring>
#include <string>
#include <type_traits>
#include <functional>
#if __cplusplus > 201402L && __has_include(<variant>) && __has_include(<optional>) // C++17
#define BRICK_TYPES_HAS_MATCH
#include <variant>
#include <optional>
#endif
#if __cplusplus >= 201103L
#define CONSTEXPR constexpr
#else
#define CONSTEXPR
#endif
#if __cplusplus > 201103L && __GNUC__ != 4 && __GNUC_MINOR__ != 9
#define CPP1Y_CONSTEXPR constexpr // C++1y
#else
#define CPP1Y_CONSTEXPR // C++11
#endif
namespace brick {
namespace types {
struct Preferred { CONSTEXPR Preferred() { } };
struct NotPreferred { CONSTEXPR NotPreferred( Preferred ) {} };
template< typename _T >
struct Witness { using T = _T; };
namespace detail
{
template< typename T >
constexpr auto _has_as_tuple( Preferred )
-> decltype( std::declval< const T & >().as_tuple(), bool() )
{ return true; }
template< typename T >
constexpr auto _has_as_tuple( NotPreferred ) { return false; }
template< typename T >
constexpr bool has_as_tuple() { return _has_as_tuple< T >( Preferred() ); }
}
// requires operator==
struct Eq { };
template< typename Trait, typename Ret, typename T >
using HasTrait = typename std::enable_if< std::is_base_of< Trait, T >::value, Ret >::type;
template< typename T >
using IsEq = HasTrait< Eq, bool, T >;
template< typename T >
IsEq< T > operator!=( const T &a, const T &b ) { return !(a == b); }
template< typename T >
auto operator==( const T &a, const T &b )
-> std::enable_if_t< detail::has_as_tuple< T >(), IsEq< T > >
{
return a.as_tuple() == b.as_tuple();
}
// requires operator <
struct Ord : Eq { };
template< typename T >
using IsOrd = HasTrait< Ord, bool, T >;
template< typename T >
IsOrd< T > operator>( const T &a, const T &b ) { return b < a; }
template< typename T >
IsOrd< T > operator>=( const T &a, const T &b ) { return !(a < b); }
template< typename T >
IsOrd< T > operator<=( const T &a, const T &b ) { return !(b < a); }
template< typename T >
auto operator==( const T &a, const T &b )
-> std::enable_if_t< !detail::has_as_tuple< T >(), IsOrd< T > >
{
return !(a < b) && !(b < a);
}
template< typename T >
auto operator<( const T &a, const T &b )
-> std::enable_if_t< detail::has_as_tuple< T >(), IsOrd< T > >
{
return a.as_tuple() < b.as_tuple();
}
using Comparable = Ord;
struct Unit : Ord {
bool operator<( Unit ) const { return false; }
bool operator==( Unit ) const { return true; }
};
struct Defer {
template< typename F >
Defer( F fn ) : fn( fn ), _deleted( false ) { }
void run() {
if ( !_deleted ) {
fn();
_deleted = true;
}
}
bool deleted() const { return _deleted; }
void pass() { _deleted = true; }
~Defer() { run(); }
private:
std::function< void() > fn;
bool _deleted;
};
template< typename T >
struct StorableRef {
T _t;
T &t() { return _t; }
const T &t() const { return _t; }
StorableRef( T t ) : _t( t ) {}
};
template< typename T >
struct StorableRef< T & > {
T *_t;
T &t() { return *_t; }
const T &t() const { return *_t; }
StorableRef( T &t ) : _t( &t ) {}
};
template< typename _T >
struct Maybe : Comparable
{
using T = _T;
bool isNothing() const { return _nothing; }
bool isJust() const { return !_nothing; }
T &value() {
ASSERT( isJust() );
return _v.t.t();
}
const T &value() const {
ASSERT( isJust() );
return _v.t.t();
}
T fromMaybe( T x ) const { return isJust() ? value() : x; }
explicit operator bool() const { return isJust() && bool( value() ); }
static Maybe Just( const T &t ) { return Maybe( t ); }
static Maybe Nothing() { return Maybe(); }
Maybe( const Maybe &m ) {
_nothing = m.isNothing();
if ( !_nothing )
_v.t = m._v.t;
}
~Maybe() {
if ( !_nothing )
_v.t.~StorableRef< T >();
}
bool operator <( const Maybe< T > &o ) const {
if ( isNothing() )
return !o.nothing();
if ( o.isNothing() )
return false;
return value() < o.value();
}
protected:
Maybe( const T &v ) : _v( v ), _nothing( false ) {}
Maybe() : _nothing( true ) {}
struct Empty {
char x[ sizeof( T ) ];
};
union V {
StorableRef< T > t;
Empty empty;
V() : empty() {}
V( const T &t ) : t( t ) {}
~V() { } // see dtor of Maybe
};
V _v;
bool _nothing;
};
template<>
struct Maybe< void > {
typedef void T;
static Maybe Just() { return Maybe( false ); }
static Maybe Nothing() { return Maybe( true ); }
bool isNothing() { return _nothing; }
bool isJust() { return !_nothing; }
private:
Maybe( bool nothing ) : _nothing( nothing ) {}
bool _nothing;
};
#if __cplusplus >= 201403L
namespace detail {
template< class... >
using void_t = void;
template< class Default, class AlwaysVoid, template< class... > class Op, class... Args >
struct Detector {
using value_t = std::false_type;
using type = Default;
};
template< class Default, template< class... > class Op, class... Args >
struct Detector< Default, void_t< Op< Args... > >, Op, Args... > {
using value_t = std::true_type;
using type = Op< Args... >;
};
} // namespace detail
struct NoneSuch {
NoneSuch() = delete;
~NoneSuch() = delete;
NoneSuch( NoneSuch const& ) = delete;
void operator=( NoneSuch const& ) = delete;
};
template< template< class... > class Op, class... Args >
using is_detected = typename detail::Detector< NoneSuch, void, Op, Args... >::value_t;
template< template< class... > class Op, class... Args >
constexpr bool is_detected_v = is_detected< Op, Args... >::value;
#endif
#if __cplusplus >= 201103L
template< typename E >
using is_enum_class = std::integral_constant< bool,
std::is_enum< E >::value && !std::is_convertible< E, int >::value >;
template< typename Self >
struct StrongEnumFlags {
static_assert( is_enum_class< Self >::value, "Not an enum class." );
using This = StrongEnumFlags< Self >;
using UnderlyingType = typename std::underlying_type< Self >::type;
constexpr StrongEnumFlags() noexcept : store( 0 ) { }
constexpr StrongEnumFlags( Self flag ) noexcept :
store( static_cast< UnderlyingType >( flag ) )
{ }
explicit constexpr StrongEnumFlags( UnderlyingType st ) noexcept : store( st ) { }
constexpr explicit operator UnderlyingType() const noexcept {
return store;
}
This &operator|=( This o ) noexcept {
store |= o.store;
return *this;
}
This &operator&=( This o ) noexcept {
store &= o.store;
return *this;
}
This &operator^=( This o ) noexcept {
store ^= o.store;
return *this;
}
friend constexpr This operator|( This a, This b ) noexcept {
return This( a.store | b.store );
}
friend constexpr This operator&( This a, This b ) noexcept {
return This( a.store & b.store );
}
friend constexpr This operator^( This a, This b ) noexcept {
return This( a.store ^ b.store );
}
friend constexpr bool operator==( This a, This b ) noexcept {
return a.store == b.store;
}
friend constexpr bool operator!=( This a, This b ) noexcept {
return a.store != b.store;
}
constexpr bool has( Self x ) const noexcept {
return ((*this) & x) == x;
}
This clear( Self x ) noexcept {
store &= ~UnderlyingType( x );
return *this;
}
explicit constexpr operator bool() const noexcept {
return store;
}
constexpr This operator~() const noexcept { return This( ~store ); }
private:
UnderlyingType store;
};
template< typename T >
brq::parse_result from_string( std::string_view s, brick::types::StrongEnumFlags< T > &f )
{
T val;
for ( auto c : brq::splitter( s, ',' ) )
{
if ( auto r = from_string( c, val ) ; !r )
return r;
else
f |= val;
}
return {};
}
/* implementation of Union */
namespace _impl {
template< size_t val, typename... >
struct MaxSizeof : std::integral_constant< size_t, val > { };
template< size_t val, typename T, typename... Ts >
struct MaxSizeof< val, T, Ts... > :
MaxSizeof< ( val > sizeof( T ) ) ? val : sizeof( T ), Ts... >
{ };
template< size_t val, typename... >
struct MaxAlign : std::integral_constant< size_t, val > { };
template< size_t val, typename T, typename... Ts >
struct MaxAlign< val, T, Ts... > :
MaxAlign< ( val > std::alignment_of< T >::value )
? val : std::alignment_of< T >::value, Ts... >
{ };
template< typename... >
struct AllDistinct : std::true_type { };
template< typename, typename... >
struct In : std::false_type { };
template< typename Needle, typename T, typename... Ts >
struct In< Needle, T, Ts... > : std::integral_constant< bool,
std::is_same< Needle, T >::value || In< Needle, Ts... >::value >
{ };
template< typename, typename... >
struct _OneConversion { };
template< typename From, typename To, typename... >
struct NoneConvertible { using T = To; };
template< typename From, typename To, typename T, typename... Ts >
struct NoneConvertible< From, To, T, Ts... > : std::conditional<
std::is_convertible< From, T >::value,
Unit,
NoneConvertible< From, To, Ts... > >::type { };
static_assert( std::is_convertible< Witness< int >, Witness< int > >::value, "is_convertible" );
template< typename Needle, typename T, typename... Ts >
struct _OneConversion< Needle, T, Ts... > : std::conditional<
std::is_convertible< Needle, T >::value,
NoneConvertible< Needle, T, Ts... >,
_OneConversion< Needle, Ts... > >::type { };
template< typename Needle, typename... Ts >
struct OneConversion : std::conditional<
In< Needle, Ts... >::value,
Witness< Needle >,
_OneConversion< Needle, Ts... > >::type { };
static_assert( std::is_same< OneConversion< int, int >::T, int >::value, "OneConversion" );
static_assert( std::is_same< OneConversion< long, int >::T, int >::value, "OneConversion" );
static_assert( std::is_same< OneConversion< long, std::string, int >::T, int >::value, "OneConversion" );
static_assert( std::is_same< OneConversion< long, int, long, int >::T, long >::value, "OneConversion" );
template< typename T, typename... Ts >
struct AllDistinct< T, Ts... > : std::integral_constant< bool,
!In< T, Ts... >::value && AllDistinct< Ts... >::value >
{ };
template< typename F, typename T, typename Fallback, typename Check = bool >
struct _ApplyResult : Fallback {};
template< typename F, typename T, typename Fallback >
struct _ApplyResult< F, T, Fallback, decltype( std::declval< F >()( std::declval< T& >() ), true ) >
{
using Parameter = T;
using Result = decltype( std::declval< F >()( std::declval< T& >() ) );
};
template< typename F, typename... Ts > struct ApplyResult;
template< typename F, typename T, typename... Ts >
struct ApplyResult< F, T, Ts... > : _ApplyResult< F, T, ApplyResult< F, Ts... > > {};
template< typename F > struct ApplyResult< F > {};
}
template< typename T >
struct InPlace { };
struct NullUnion { };
namespace _impl {
template< bool AllowCopy, typename... Types >
struct Union : Comparable
{
static_assert( sizeof...( Types ) < 0xff, "Too much unioned types, sorry" );
static_assert( _impl::AllDistinct< Types... >::value,
"All types in union must be distinct" );
constexpr Union() : _discriminator( 0 ) { }
constexpr Union( NullUnion ) : _discriminator( 0 ) { }
Union( const Union &other ) {
ASSERT_LEQ( size_t( other._discriminator ), sizeof...( Types ) );
if ( other._discriminator > 0 )
_copyConstruct< 1, Types... >( other._discriminator, other );
_discriminator = other._discriminator;
}
Union( Union &&other ) {
ASSERT_LEQ( size_t( other._discriminator ), sizeof...( Types ) );
auto target = other._discriminator;
other._discriminator = 0;
if ( target > 0 )
_moveConstruct< 1, Types... >( target, std::move( other ) );
_discriminator = target;
}
template< typename T, typename U = typename _impl::OneConversion< T, Types... >::T >
CPP1Y_CONSTEXPR Union( T val ) {
new ( &storage ) U( std::move( val ) );
_discriminator = discriminator< U >();
}
template< typename T, typename... Args >
Union( InPlace< T >, Args &&... args ) : _discriminator( discriminator< T >() ) {
new ( &storage ) T( std::forward< Args >( args )... );
}
// use copy and swap
Union &operator=( Union other ) {
swap( other );
return *this;
}
~Union() {
if ( _discriminator )
_destruct< 1, Types... >( _discriminator );
}
template< typename T >
auto operator=( const T &other ) -> typename
std::enable_if< std::is_lvalue_reference< T & >::value, Union & >::type
{
if ( is< T >() )
unsafeGet< T >() = other;
else
_copyAssignDifferent( Union( other ) );
return *this;
}
template< typename T >
auto operator=( T &&other ) -> typename
std::enable_if< std::is_rvalue_reference< T && >::value, Union & >::type
{
if ( is< T >() )
unsafeGet< T >() = std::move( other );
else
_moveAssignDifferent( std::move( other ) );
return *this;
}
void swap( Union &other ) {
if ( _discriminator == 0 && other._discriminator == 0 )
return;
if ( _discriminator == other._discriminator )
_swapSame< 1, Types... >( other );
else
_swapDifferent< 0, void, Types... >( other );
}
bool empty() const {
return _discriminator == 0;
}
explicit operator bool() const
{
auto rv = const_cast< Union* >( this )->apply( []( const auto & x ) -> bool { return !!x; } );
if ( rv.isNothing() )
return false;
return true;
}
template< typename T >
bool is() const {
return discriminator< T >() == _discriminator;
}
template< typename T >
explicit operator T() const {
return convert< T >();
}
template< typename T >
T &get() {
ASSERT( is< T >() );
return unsafeGet< T >();
}
template< typename T >
const T &get() const {
return cget< T >();
}
template< typename T >
const T &cget() const {
ASSERT( is< T >() );
return unsafeGet< T >();
}
template< typename T >
T *asptr() { return is< T >() ? &get< T >() : nullptr; }
template< typename T >
const T *asptr() const { return is< T >() ? &get< T >() : nullptr; }
template< typename T >
const T &getOr( const T &val ) const {
if ( is< T >() )
return unsafeGet< T >();
return val;
}
template< typename T >
T convert() const { return _convert< T >(); }
template< typename T >
T &unsafeGet() {
return *reinterpret_cast< T * >( &storage );
}
template< typename T >
const T &unsafeGet() const {
return *reinterpret_cast< const T * >( &storage );
}
template< typename T >
T &&moveOut() {
ASSERT( is< T >() );
return unsafeMoveOut< T >();
}
template< typename T >
T &&unsafeMoveOut() {
return std::move( *reinterpret_cast< T * >( &storage ) );
}
template< typename F >
using Applied = Maybe< typename _impl::ApplyResult< F, Types... >::Result >;
// invoke `f` on the stored value if the type currently stored in the union
// can be legally passed to that function as an argument
template< typename F >
auto apply( F f ) -> Applied< F > {
return _apply< F, Types... >( Preferred(), f );
}
template< typename R >
R _match() { return R::Nothing(); }
// invoke the first function that can handle the currently stored value
// (type-based pattern matching)
template< typename R, typename F, typename... Args >
R _match( F f, Args&&... args ) {
auto x = apply( f );
if ( x.isNothing() )
return _match< R >( args... );
else
return x;
}
// invoke the first function that can handle the currently stored value
// (type-based pattern matching)
// * return value can be extracted from resuling Maybe value
// * auto lambdas are supported an can be called on any value!
template< typename F, typename... Args >
Applied< F > match( F f, Args&&... args ) {
return _match< Applied< F > >( f, args... );
}
bool operator==( const Union &other ) const {
return _discriminator == other._discriminator
&& (_discriminator == 0 || _compare< std::equal_to >( other ));
}
bool operator<( const Union &other ) const {
return _discriminator < other._discriminator
|| (_discriminator == other._discriminator
&& (_discriminator == 0 || _compare< std::less >( other )) );
}
unsigned char discriminator() const { return _discriminator; }
template< typename T >
unsigned char discriminator() const {
static_assert( _impl::In< T, Types... >::value,
"Trying to construct Union from value of type not allowed for it." );
return _discriminatorF< 1, T, Types... >();
}
private:
static constexpr size_t size = _impl::MaxSizeof< 1, Types... >::value;
static constexpr size_t alignment = _impl::MaxAlign< 1, Types... >::value;
typename std::aligned_storage< size, alignment >::type storage;
unsigned char _discriminator;
template< unsigned char i, typename Needle, typename T, typename... Ts >
constexpr unsigned char _discriminatorF() const {
return std::is_same< Needle, T >::value
? i : _discriminatorF< i + 1, Needle, Ts... >();
}
template< unsigned char, typename >
constexpr unsigned char _discriminatorF() const { return 0; /* cannot happen */ }
template< unsigned char i, typename T, typename... Ts >
void _copyConstruct( unsigned char d, const Union &other ) {
if ( i == d )
new ( &storage ) T( other.unsafeGet< T >() );
else
_copyConstruct< i + 1, Ts... >( d, other );
}
template< unsigned char >
unsigned char _copyConstruct( unsigned char, const Union & )
{ UNREACHABLE( "invalid _copyConstruct" ); }
template< unsigned char i, typename T, typename... Ts >
void _moveConstruct( unsigned char d, Union &&other ) {
if ( i == d )
new ( &storage ) T( other.unsafeMoveOut< T >() );
else
_moveConstruct< i + 1, Ts... >( d, std::move( other ) );
}
template< unsigned char >
unsigned char _moveConstruct( unsigned char, Union && )
{ UNREACHABLE( "invalid _moveConstruct" ); }
void _copyAssignDifferent( const Union &other ) {
auto tmp = _discriminator;
_discriminator = 0;
if ( tmp )
_destruct< 1, Types... >( tmp );
if ( other._discriminator )
_copyConstruct< 1, Types... >( other._discriminator, other );
_discriminator = other._discriminator;
}
void _copyAssignSame( const Union &other ) {
ASSERT_EQ( _discriminator, other._discriminator );
if ( _discriminator == 0 )
return;
_copyAssignSame< 1, Types... >( other );
}
template< unsigned char i, typename T, typename... Ts >
void _copyAssignSame( const Union &other ) {
if ( i == _discriminator )
unsafeGet< T >() = other.unsafeGet< T >();
else
_copyAssignSame< i + 1, Ts... >( other );
}
template< unsigned char >
void _copyAssignSame( const Union & ) { UNREACHABLE( "invalid _copyAssignSame" ); }
template< unsigned char i, typename T, typename... Ts >
void _destruct( unsigned char d ) {
if ( i == d )
unsafeGet< T >().~T();
else
_destruct< i + 1, Ts... >( d );
}
template< unsigned char >
void _destruct( unsigned char ) { UNREACHABLE( "invalid _destruct" ); }
void _moveAssignSame( Union &&other ) {
ASSERT_EQ( _discriminator, other._discriminator );
if ( _discriminator == 0 )
return;
_moveAssignSame< 1, Types... >( std::move( other ) );
}
template< unsigned char i, typename T, typename... Ts >
void _moveAssignSame( Union &&other ) {
if ( i == _discriminator )
unsafeGet< T >() = other.unsafeMoveOut< T >();
else
_moveAssignSame< i + 1, Ts... >( std::move( other ) );
}
template< unsigned char >
void _moveAssignSame( Union && ) { UNREACHABLE( "invalid _moveAssignSame" ); }
void _moveAssignDifferent( Union &&other ) {
auto tmp = _discriminator;
auto target = other._discriminator;
_discriminator = 0;
if ( tmp )
_destruct< 1, Types... >( tmp );
if ( target )
_moveConstruct< 1, Types... >( target, std::move( other ) );
_discriminator = target;
}
template< typename F > Applied< F > _apply( Preferred, F ) { return Applied< F >::Nothing(); }
template< typename F, typename T >
auto fixvoid( F f ) ->
typename std::enable_if< std::is_void< typename Applied< F >::T >::value, Applied< F > >::type
{
f( get< T >() );
return Maybe< void >::Just();
}
template< typename F, typename T >
auto fixvoid( F f ) ->
typename std::enable_if< !std::is_void< typename Applied< F >::T >::value, Applied< F > >::type
{
return Applied< F >::Just( f( get< T >() ) );
}
template< typename F, typename T, typename... Args >
auto _apply( Preferred, F f ) -> Maybe< typename _impl::_ApplyResult< F, T, Unit >::Result >
{
if ( !is< T >() )
return _apply< F, Args... >( Preferred(), f );
return fixvoid< F, T >( f );
}
template< typename F, typename T, typename... Args >
auto _apply( NotPreferred, F f ) -> Applied< F >
{
return _apply< F, Args... >( Preferred(), f );
}
template< template< typename > class Compare, int d >
bool _compare2( const Union & ) const { UNREACHABLE( "invalid discriminator" ); }
template< template< typename > class Compare, int d, typename T, typename... Ts >
bool _compare2( const Union &other ) const {
return d == _discriminator
? Compare< T >()( get< T >(), other.template get< T >() )
: _compare2< Compare, d + 1, Ts... >( other );
}
template< template< typename > class Compare >
bool _compare( const Union &other ) const {
return _compare2< Compare, 1, Types... >( other );
}
template< typename Target, bool anyCastPossible, int >
Target _convert2( Preferred ) const {
static_assert( anyCastPossible, "Cast of Union can never succeed" );
UNREACHABLE( "wrong _convert2 in Union" );
}
template< typename Target, bool any, int d, typename, typename... Ts >
Target _convert2( NotPreferred ) const {
return _convert2< Target, any, d + 1, Ts... >( Preferred() );
}
template< typename Target, bool any, int d, typename T, typename... Ts >
auto _convert2( Preferred ) const -> decltype( static_cast< Target >( this->unsafeGet< T >() ) )
{
if ( _discriminator == d )
return static_cast< Target >( unsafeGet< T >() );
return _convert2< Target, true, d + 1, Ts... >( Preferred() );
}
template< typename Target >
Target _convert() const {
return _convert2< Target, false, 1, Types... >( Preferred() );
}
template< unsigned char i, typename T, typename... Ts >
void _swapSame( Union &other ) {
if ( _discriminator == i )
_doSwap< T >( unsafeGet< T >(), other.unsafeGet< T >(), Preferred() );
else
_swapSame< i + 1, Ts... >( other );
}
template< unsigned char i >
void _swapSame( Union & ) { UNREACHABLE( "Invalid _swapSame" ); }
template< typename T >
auto _doSwap( T &a, T &b, Preferred ) -> decltype( a.swap( b ) ) {
a.swap( b );
}
template< typename T >
auto _doSwap( T &a, T &b, NotPreferred ) -> decltype( std::swap( a, b ) ) {
std::swap( a, b );
}
template< unsigned char i, typename T, typename... Ts >
void _swapDifferent( Union &other ) {
if ( i == _discriminator )
_swapDifferent2< i, T, 0, void, Types... >( other );
else
_swapDifferent< i + 1, Ts... >( other );
}
template< unsigned char i >
void _swapDifferent( Union & ) { UNREACHABLE( "Invalid _swapDifferent" ); }
template< unsigned char local, typename Local, unsigned char i, typename T, typename... Ts >
void _swapDifferent2( Union &other ) {
if ( i == other._discriminator )
_doSwapDifferent< local, i, Local, T >( other );
else
_swapDifferent2< local, Local, i + 1, Ts... >( other );
}
template< unsigned char local, typename Local, unsigned char i >
void _swapDifferent2( Union & ) { UNREACHABLE( "Invalid _swapDifferent2" ); }
template< unsigned char l, unsigned char r, typename L, typename R >
auto _doSwapDifferent( Union &other ) -> typename std::enable_if< l != 0 && r != 0 >::type {
L lval( unsafeMoveOut< L >() );
unsafeGet< L >().~L();
new ( &unsafeGet< R >() ) R( other.unsafeMoveOut< R >() );
other.unsafeGet< R >().~R();
new ( &other.unsafeGet< L >() ) L( std::move( lval ) );
std::swap( _discriminator, other._discriminator );
}
template< unsigned char l, unsigned char r, typename L, typename R >
auto _doSwapDifferent( Union &other ) -> typename std::enable_if< l == 0 && r != 0 >::type {
new ( &unsafeGet< R >() ) R( other.unsafeMoveOut< R >() );
other.unsafeGet< R >().~R();
std::swap( _discriminator, other._discriminator );
}
template< unsigned char l, unsigned char r, typename L, typename R >
auto _doSwapDifferent( Union &other ) -> typename std::enable_if< l != 0 && r == 0 >::type {
new ( &other.unsafeGet< L >() ) L( unsafeMoveOut< L >() );
unsafeGet< L >().~L();
std::swap( _discriminator, other._discriminator );
}
template< unsigned char l, unsigned char r, typename L, typename R >
auto _doSwapDifferent( Union & ) -> typename std::enable_if< l == 0 && r == 0 >::type {
UNREACHABLE( "Invalid _doSwapDifferent" );
}
};
template< typename... Types >
struct Union< false, Types... > : Union< true, Types... >
{
using Union< true, Types... >::Union;
using Union< true, Types... >::operator=;
Union( const Union & ) = delete;
Union( Union && ) = default;
Union() = default;
template< typename T >
Union &operator=( const T &other ) = delete;
Union &operator=( Union && ) = default;
};
}
template< typename... Types >
using Union = _impl::Union< ( std::is_copy_constructible< Types >::value && ... ), Types... >;
template< typename Left, typename Right >
struct Either : Union< Left, Right > {
using Union< Left, Right >::Union;
bool isLeft() const { return this->template is< Left >(); }
bool isRight() const { return this->template is< Right >(); }
Left &left() { return this->template get< Left >(); }
Right &right() { return this->template get< Right >(); }
const Left &left() const { return this->template get< Left >(); }
const Right &right() const { return this->template get< Right >(); }
};
// a pointer-like structure which can, however store values a value or a
// referrence to type T
template< typename T >
struct RefOrVal {
static_assert( !std::is_reference< T >::value, "T must not be a reference type" );
RefOrVal() : _store( InPlace< T >() ) { }
RefOrVal( T &&val ) : _store( std::forward< T >( val ) ) { }
RefOrVal( T *ref ) : _store( ref ) { }
RefOrVal( T &ref ) : _store( &ref ) { }
RefOrVal &operator=( const RefOrVal & ) = default;
RefOrVal &operator=( RefOrVal && ) = default;
RefOrVal &operator=( T &v ) { _store = v; return *this; }
RefOrVal &operator=( T &&v ) { _store = std::move( v ); return *this; }
RefOrVal &operator=( T *ptr ) { _store = ptr; return *this; }
T *ptr() {
ASSERT( !_store.empty() );
auto *val = _store.template asptr< T >();
return val ? val : _store.template get< T * >();
}
const T *ptr() const {
ASSERT( !_store.empty() );
const auto *val = _store.template asptr< T >();
return val ? val : _store.template get< T * >();
}
T *operator->() { return ptr(); }
T &operator*() { return *ptr(); }
const T *operator->() const { return ptr(); }
const T &operator*() const { return *ptr(); }
private:
Union< T, T * > _store;
};
template< typename Fn, typename R = typename std::invoke_result_t< Fn > >