/
Expected.h
1384 lines (1248 loc) · 43.5 KB
/
Expected.h
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
/*
* Copyright 2016 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Like folly::Optional, but can store a value *or* and error.
*
* @author Eric Niebler (eniebler@fb.com)
*/
#pragma once
#include <cstddef>
#include <initializer_list>
#include <new>
#include <stdexcept>
#include <type_traits>
#include <utility>
#include <folly/Likely.h>
#include <folly/Portability.h>
#include <folly/Preprocessor.h>
#include <folly/Traits.h> // for construct_in_place_t
#include <folly/Unit.h>
#define FOLLY_EXPECTED_ID(X) FB_CONCATENATE(FB_CONCATENATE(Folly, X), __LINE__)
#define FOLLY_REQUIRES_IMPL(...) \
bool FOLLY_EXPECTED_ID(Requires) = false, \
typename std::enable_if< \
(FOLLY_EXPECTED_ID(Requires) || static_cast<bool>(__VA_ARGS__)), \
int>::type = 0
#define FOLLY_REQUIRES_TRAILING(...) , FOLLY_REQUIRES_IMPL(__VA_ARGS__)
#define FOLLY_REQUIRES(...) template <FOLLY_REQUIRES_IMPL(__VA_ARGS__)>
/**
* gcc-4.7 warns about use of uninitialized memory around the use of storage_
* even though this is explicitly initialized at each point.
*/
#if defined(__GNUC__) && !defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wuninitialized"
#pragma GCC diagnostic ignored "-Wpragmas"
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
#endif // __GNUC__
namespace folly {
/**
* Forward declarations
*/
template <class Error>
class Unexpected;
template <class Error>
constexpr Unexpected<typename std::decay<Error>::type> makeUnexpected(Error&&);
template <class Value, class Error>
class Expected;
template <class Error, class Value>
constexpr Expected<typename std::decay<Value>::type, Error> makeExpected(
Value&&);
/**
* Alias for an Expected type's assiciated value_type
*/
template <class Expected>
using ExpectedValueType =
typename std::remove_reference<Expected>::type::value_type;
/**
* Alias for an Expected type's assiciated error_type
*/
template <class Expected>
using ExpectedErrorType =
typename std::remove_reference<Expected>::type::error_type;
// Details...
namespace expected_detail {
#ifdef _MSC_VER
// MSVC 2015 can't handle the StrictConjunction, so we have
// to use std::conjunction instead.
template <template <class...> class Trait, class... Ts>
using StrictAllOf = std::conjunction<Trait<Ts>...>;
#else
template <template <class...> class Trait, class... Ts>
using StrictAllOf = StrictConjunction<Trait<Ts>...>;
#endif
template <class T>
using IsCopyable = StrictConjunction<
std::is_copy_constructible<T>,
std::is_copy_assignable<T>>;
template <class T>
using IsMovable = StrictConjunction<
std::is_move_constructible<T>,
std::is_move_assignable<T>>;
template <class T>
using IsNothrowCopyable = StrictConjunction<
std::is_nothrow_copy_constructible<T>,
std::is_nothrow_copy_assignable<T>>;
template <class T>
using IsNothrowMovable = StrictConjunction<
std::is_nothrow_move_constructible<T>,
std::is_nothrow_move_assignable<T>>;
template <class From, class To>
using IsConvertible = StrictConjunction<
std::is_constructible<To, From>,
std::is_assignable<To&, From>>;
template <class T, class U>
auto doEmplaceAssign(int, T& t, U&& u) -> decltype(void(t = (U &&)u)) {
t = (U &&)u;
}
template <class T, class U>
auto doEmplaceAssign(long, T& t, U&& u) -> decltype(void(T((U &&)u))) {
t.~T();
::new ((void*)std::addressof(t)) T((U &&)u);
}
template <class T, class... Us>
auto doEmplaceAssign(int, T& t, Us&&... us)
-> decltype(void(t = T((Us &&)us...))) {
t = T((Us &&)us...);
}
template <class T, class... Us>
auto doEmplaceAssign(long, T& t, Us&&... us)
-> decltype(void(T((Us &&)us...))) {
t.~T();
::new ((void*)std::addressof(t)) T((Us &&)us...);
}
struct EmptyTag {};
struct ValueTag {};
struct ErrorTag {};
enum class Which : unsigned char { eEmpty, eValue, eError };
enum class StorageType { ePODStruct, ePODUnion, eUnion };
template <class Value, class Error>
constexpr StorageType getStorageType() {
return StrictAllOf<IsTriviallyCopyable, Value, Error>::value
? (sizeof(std::pair<Value, Error>) <= sizeof(void * [2]) &&
StrictAllOf<std::is_trivial, Value, Error>::value
? StorageType::ePODStruct
: StorageType::ePODUnion)
: StorageType::eUnion;
}
template <
class Value,
class Error,
StorageType = expected_detail::getStorageType<Value, Error>()> // ePODUnion
struct ExpectedStorage {
using value_type = Value;
using error_type = Error;
union {
Value value_;
Error error_;
char ch_;
};
Which which_;
template <class E = Error, class = decltype(E{})>
constexpr ExpectedStorage() noexcept(noexcept(E{}))
: error_{}, which_(Which::eError) {}
explicit constexpr ExpectedStorage(EmptyTag) noexcept
: ch_{}, which_(Which::eEmpty) {}
template <class... Vs>
explicit constexpr ExpectedStorage(ValueTag, Vs&&... vs) noexcept(
noexcept(Value(static_cast<Vs&&>(vs)...)))
: value_(static_cast<Vs&&>(vs)...), which_(Which::eValue) {}
template <class... Es>
explicit constexpr ExpectedStorage(ErrorTag, Es&&... es) noexcept(
noexcept(Error(static_cast<Es&&>(es)...)))
: error_(static_cast<Es&&>(es)...), which_(Which::eError) {}
void clear() noexcept {}
static constexpr bool uninitializedByException() noexcept {
// Although which_ may temporarily be eEmpty during construction, it
// is always either eValue or eError for a fully-constructed Expected.
return false;
}
template <class... Vs>
void assignValue(Vs&&... vs) {
expected_detail::doEmplaceAssign(0, value_, static_cast<Vs&&>(vs)...);
which_ = Which::eValue;
}
template <class... Es>
void assignError(Es&&... es) {
expected_detail::doEmplaceAssign(0, error_, static_cast<Es&&>(es)...);
which_ = Which::eError;
}
template <class Other>
void assign(Other&& that) {
switch (that.which_) {
case Which::eValue:
this->assignValue(static_cast<Other&&>(that).value());
break;
case Which::eError:
this->assignError(static_cast<Other&&>(that).error());
break;
default:
this->clear();
break;
}
}
Value& value() & {
return value_;
}
const Value& value() const& {
return value_;
}
Value&& value() && {
return std::move(value_);
}
Error& error() & {
return error_;
}
const Error& error() const& {
return error_;
}
Error&& error() && {
return std::move(error_);
}
};
template <class Value, class Error>
struct ExpectedUnion {
union {
Value value_;
Error error_;
char ch_{};
};
Which which_ = Which::eEmpty;
explicit constexpr ExpectedUnion(EmptyTag) noexcept {}
template <class... Vs>
explicit constexpr ExpectedUnion(ValueTag, Vs&&... vs) noexcept(
noexcept(Value(static_cast<Vs&&>(vs)...)))
: value_(static_cast<Vs&&>(vs)...), which_(Which::eValue) {}
template <class... Es>
explicit constexpr ExpectedUnion(ErrorTag, Es&&... es) noexcept(
noexcept(Error(static_cast<Es&&>(es)...)))
: error_(static_cast<Es&&>(es)...), which_(Which::eError) {}
ExpectedUnion(const ExpectedUnion&) {}
ExpectedUnion(ExpectedUnion&&) noexcept {}
ExpectedUnion& operator=(const ExpectedUnion&) {
return *this;
}
ExpectedUnion& operator=(ExpectedUnion&&) noexcept {
return *this;
}
~ExpectedUnion() {}
Value& value() & {
return value_;
}
const Value& value() const& {
return value_;
}
Value&& value() && {
return std::move(value_);
}
Error& error() & {
return error_;
}
const Error& error() const& {
return error_;
}
Error&& error() && {
return std::move(error_);
}
};
template <class Derived, bool, bool Noexcept>
struct CopyConstructible {
constexpr CopyConstructible() = default;
CopyConstructible(const CopyConstructible& that) noexcept(Noexcept) {
static_cast<Derived*>(this)->assign(static_cast<const Derived&>(that));
}
constexpr CopyConstructible(CopyConstructible&&) = default;
CopyConstructible& operator=(const CopyConstructible&) = default;
CopyConstructible& operator=(CopyConstructible&&) = default;
};
template <class Derived, bool Noexcept>
struct CopyConstructible<Derived, false, Noexcept> {
constexpr CopyConstructible() = default;
CopyConstructible(const CopyConstructible&) = delete;
constexpr CopyConstructible(CopyConstructible&&) = default;
CopyConstructible& operator=(const CopyConstructible&) = default;
CopyConstructible& operator=(CopyConstructible&&) = default;
};
template <class Derived, bool, bool Noexcept>
struct MoveConstructible {
constexpr MoveConstructible() = default;
constexpr MoveConstructible(const MoveConstructible&) = default;
MoveConstructible(MoveConstructible&& that) noexcept(Noexcept) {
static_cast<Derived*>(this)->assign(std::move(static_cast<Derived&>(that)));
}
MoveConstructible& operator=(const MoveConstructible&) = default;
MoveConstructible& operator=(MoveConstructible&&) = default;
};
template <class Derived, bool Noexcept>
struct MoveConstructible<Derived, false, Noexcept> {
constexpr MoveConstructible() = default;
constexpr MoveConstructible(const MoveConstructible&) = default;
MoveConstructible(MoveConstructible&&) = delete;
MoveConstructible& operator=(const MoveConstructible&) = default;
MoveConstructible& operator=(MoveConstructible&&) = default;
};
template <class Derived, bool, bool Noexcept>
struct CopyAssignable {
constexpr CopyAssignable() = default;
constexpr CopyAssignable(const CopyAssignable&) = default;
constexpr CopyAssignable(CopyAssignable&&) = default;
CopyAssignable& operator=(const CopyAssignable& that) noexcept(Noexcept) {
static_cast<Derived*>(this)->assign(static_cast<const Derived&>(that));
return *this;
}
CopyAssignable& operator=(CopyAssignable&&) = default;
};
template <class Derived, bool Noexcept>
struct CopyAssignable<Derived, false, Noexcept> {
constexpr CopyAssignable() = default;
constexpr CopyAssignable(const CopyAssignable&) = default;
constexpr CopyAssignable(CopyAssignable&&) = default;
CopyAssignable& operator=(const CopyAssignable&) = delete;
CopyAssignable& operator=(CopyAssignable&&) = default;
};
template <class Derived, bool, bool Noexcept>
struct MoveAssignable {
constexpr MoveAssignable() = default;
constexpr MoveAssignable(const MoveAssignable&) = default;
constexpr MoveAssignable(MoveAssignable&&) = default;
MoveAssignable& operator=(const MoveAssignable&) = default;
MoveAssignable& operator=(MoveAssignable&& that) noexcept(Noexcept) {
static_cast<Derived*>(this)->assign(std::move(static_cast<Derived&>(that)));
return *this;
}
};
template <class Derived, bool Noexcept>
struct MoveAssignable<Derived, false, Noexcept> {
constexpr MoveAssignable() = default;
constexpr MoveAssignable(const MoveAssignable&) = default;
constexpr MoveAssignable(MoveAssignable&&) = default;
MoveAssignable& operator=(const MoveAssignable&) = default;
MoveAssignable& operator=(MoveAssignable&& that) = delete;
};
template <class Value, class Error>
struct ExpectedStorage<Value, Error, StorageType::eUnion>
: ExpectedUnion<Value, Error>,
CopyConstructible<
ExpectedStorage<Value, Error, StorageType::eUnion>,
StrictAllOf<std::is_copy_constructible, Value, Error>::value,
StrictAllOf<std::is_nothrow_copy_constructible, Value, Error>::value>,
MoveConstructible<
ExpectedStorage<Value, Error, StorageType::eUnion>,
StrictAllOf<std::is_move_constructible, Value, Error>::value,
StrictAllOf<std::is_nothrow_move_constructible, Value, Error>::value>,
CopyAssignable<
ExpectedStorage<Value, Error, StorageType::eUnion>,
StrictAllOf<IsCopyable, Value, Error>::value,
StrictAllOf<IsNothrowCopyable, Value, Error>::value>,
MoveAssignable<
ExpectedStorage<Value, Error, StorageType::eUnion>,
StrictAllOf<IsMovable, Value, Error>::value,
StrictAllOf<IsNothrowMovable, Value, Error>::value> {
using value_type = Value;
using error_type = Error;
using Base = ExpectedUnion<Value, Error>;
template <class E = Error, class = decltype(E{})>
constexpr ExpectedStorage() noexcept(noexcept(E{})) : Base{ErrorTag{}} {}
ExpectedStorage(const ExpectedStorage&) = default;
ExpectedStorage(ExpectedStorage&&) = default;
ExpectedStorage& operator=(const ExpectedStorage&) = default;
ExpectedStorage& operator=(ExpectedStorage&&) = default;
using ExpectedUnion<Value, Error>::ExpectedUnion;
~ExpectedStorage() {
clear();
}
void clear() noexcept {
switch (this->which_) {
case Which::eValue:
this->value().~Value();
break;
case Which::eError:
this->error().~Error();
break;
default:
break;
}
this->which_ = Which::eEmpty;
}
bool uninitializedByException() const noexcept {
return this->which_ == Which::eEmpty;
}
template <class... Vs>
void assignValue(Vs&&... vs) {
if (this->which_ == Which::eValue) {
expected_detail::doEmplaceAssign(
0, this->value(), static_cast<Vs&&>(vs)...);
} else {
this->clear();
::new ((void*)std::addressof(this->value()))
Value(static_cast<Vs&&>(vs)...);
this->which_ = Which::eValue;
}
}
template <class... Es>
void assignError(Es&&... es) {
if (this->which_ == Which::eError) {
expected_detail::doEmplaceAssign(
0, this->error(), static_cast<Es&&>(es)...);
} else {
this->clear();
::new ((void*)std::addressof(this->error()))
Error(static_cast<Es&&>(es)...);
this->which_ = Which::eError;
}
}
bool isThis(const ExpectedStorage* that) const {
return this == that;
}
constexpr bool isSelfAssign(const void*) const {
return false;
}
template <class Other>
void assign(Other&& that) {
if (isSelfAssign(&that))
return;
switch (that.which_) {
case Which::eValue:
this->assignValue(static_cast<Other&&>(that).value());
break;
case Which::eError:
this->assignError(static_cast<Other&&>(that).error());
break;
default:
this->clear();
break;
}
}
};
// For small (pointer-sized) trivial types, a struct is faster than a union.
template <class Value, class Error>
struct ExpectedStorage<Value, Error, StorageType::ePODStruct> {
using value_type = Value;
using error_type = Error;
Which which_;
Error error_;
Value value_;
constexpr ExpectedStorage() noexcept
: which_(Which::eError), error_{}, value_{} {}
explicit constexpr ExpectedStorage(EmptyTag) noexcept
: which_(Which::eEmpty), error_{}, value_{} {}
template <class... Vs>
explicit constexpr ExpectedStorage(ValueTag, Vs&&... vs) noexcept(
noexcept(Value(static_cast<Vs&&>(vs)...)))
: which_(Which::eValue), error_{}, value_(static_cast<Vs&&>(vs)...) {}
template <class... Es>
explicit constexpr ExpectedStorage(ErrorTag, Es&&... es) noexcept(
noexcept(Error(static_cast<Es&&>(es)...)))
: which_(Which::eError), error_(static_cast<Es&&>(es)...), value_{} {}
void clear() noexcept {}
constexpr static bool uninitializedByException() noexcept {
return false;
}
template <class... Vs>
void assignValue(Vs&&... vs) {
expected_detail::doEmplaceAssign(0, value_, static_cast<Vs&&>(vs)...);
which_ = Which::eValue;
}
template <class... Es>
void assignError(Es&&... es) {
expected_detail::doEmplaceAssign(0, error_, static_cast<Es&&>(es)...);
which_ = Which::eError;
}
template <class Other>
void assign(Other&& that) {
switch (that.which_) {
case Which::eValue:
this->assignValue(static_cast<Other&&>(that).value());
break;
case Which::eError:
this->assignError(static_cast<Other&&>(that).error());
break;
default:
this->clear();
break;
}
}
Value& value() & {
return value_;
}
const Value& value() const& {
return value_;
}
Value&& value() && {
return std::move(value_);
}
Error& error() & {
return error_;
}
const Error& error() const& {
return error_;
}
Error&& error() && {
return std::move(error_);
}
};
namespace expected_detail_ExpectedHelper {
// Tricky hack so that Expected::then can handle lambdas that return void
template <class T>
inline T&& operator,(T&& t, Unit) noexcept {
return static_cast<T&&>(t);
}
struct ExpectedHelper {
template <class Error, class T>
static constexpr Expected<T, Error> return_(T t) {
return folly::makeExpected<Error>(t);
}
template <
class Error,
class T,
class U FOLLY_REQUIRES_TRAILING(
expected_detail::IsConvertible<U&&, Error>::value)>
static constexpr Expected<T, Error> return_(Expected<T, U> t) {
return t;
}
template <class This>
static typename std::decay<This>::type then_(This&& ex) {
return static_cast<This&&>(ex);
}
FOLLY_PUSH_WARNING
// Don't warn about not using the overloaded comma operator.
FOLLY_MSVC_DISABLE_WARNING(4913)
template <
class This,
class Fn,
class... Fns,
class E = ExpectedErrorType<This>,
class T = ExpectedHelper>
static auto then_(This&& ex, Fn&& fn, Fns&&... fns) -> decltype(T::then_(
T::template return_<E>(
(std::declval<Fn>()(std::declval<This>().value()), unit)),
std::declval<Fns>()...)) {
if (LIKELY(ex.which_ == expected_detail::Which::eValue))
return T::then_(
T::template return_<E>(
// Uses the comma operator defined above IFF the lambda
// returns non-void.
(static_cast<Fn&&>(fn)(static_cast<This&&>(ex).value()), unit)),
static_cast<Fns&&>(fns)...);
return makeUnexpected(static_cast<This&&>(ex).error());
}
template <
class This,
class Yes,
class No,
class Ret = decltype(std::declval<Yes>()(std::declval<This>().value())),
class Err = decltype(std::declval<No>()(std::declval<This>().error()))
FOLLY_REQUIRES_TRAILING(!std::is_void<Err>::value)>
static Ret thenOrThrow_(This&& ex, Yes&& yes, No&& no) {
if (LIKELY(ex.which_ == expected_detail::Which::eValue))
return Ret(static_cast<Yes&&>(yes)(static_cast<This&&>(ex).value()));
throw static_cast<No&&>(no)(static_cast<This&&>(ex).error());
}
template <
class This,
class Yes,
class No,
class Ret = decltype(std::declval<Yes>()(std::declval<This>().value())),
class Err = decltype(std::declval<No>()(std::declval<This&>().error()))
FOLLY_REQUIRES_TRAILING(std::is_void<Err>::value)>
static Ret thenOrThrow_(This&& ex, Yes&& yes, No&& no) {
if (LIKELY(ex.which_ == expected_detail::Which::eValue))
return Ret(static_cast<Yes&&>(yes)(static_cast<This&&>(ex).value()));
static_cast<No&&>(no)(ex.error());
throw typename Unexpected<ExpectedErrorType<This>>::MakeBadExpectedAccess()(
static_cast<This&&>(ex).error());
}
FOLLY_POP_WARNING
};
}
/* using override */ using expected_detail_ExpectedHelper::ExpectedHelper;
struct UnexpectedTag {};
} // namespace expected_detail
using unexpected_t =
expected_detail::UnexpectedTag (&)(expected_detail::UnexpectedTag);
inline expected_detail::UnexpectedTag unexpected(
expected_detail::UnexpectedTag = {}) {
return {};
}
/**
* An exception type thrown by Expected on catastrophic logic errors.
*/
class BadExpectedAccess : public std::logic_error {
public:
BadExpectedAccess() : std::logic_error("bad Expected access") {}
};
/**
* Unexpected - a helper type used to disambiguate the construction of
* Expected objects in the error state.
*/
template <class Error>
class Unexpected final {
template <class E>
friend class Unexpected;
template <class V, class E>
friend class Expected;
friend struct expected_detail::ExpectedHelper;
public:
/**
* Unexpected::BadExpectedAccess - An exception type thrown by Expected
* when the user tries to access the nested value but the Expected object is
* actually storing an error code.
*/
class BadExpectedAccess : public folly::BadExpectedAccess {
public:
explicit BadExpectedAccess(Error err)
: folly::BadExpectedAccess{}, error_(std::move(err)) {}
/**
* The error code that was held by the Expected object when the user
* erroneously requested the value.
*/
Error error() const {
return error_;
}
private:
Error error_;
};
/**
* Constructors
*/
Unexpected() = default;
Unexpected(const Unexpected&) = default;
Unexpected(Unexpected&&) = default;
Unexpected& operator=(const Unexpected&) = default;
Unexpected& operator=(Unexpected&&) = default;
constexpr /* implicit */ Unexpected(const Error& err) : error_(err) {}
constexpr /* implicit */ Unexpected(Error&& err) : error_(std::move(err)) {}
template <class Other FOLLY_REQUIRES_TRAILING(
std::is_constructible<Error, Other&&>::value)>
constexpr /* implicit */ Unexpected(Unexpected<Other> that)
: error_(std::move(that.error())) {}
/**
* Assignment
*/
template <class Other FOLLY_REQUIRES_TRAILING(
std::is_assignable<Error&, Other&&>::value)>
Unexpected& operator=(Unexpected<Other> that) {
error_ = std::move(that.error());
}
/**
* Observers
*/
Error& error() & {
return error_;
}
const Error& error() const& {
return error_;
}
Error&& error() && {
return std::move(error_);
}
private:
struct MakeBadExpectedAccess {
template <class E>
BadExpectedAccess operator()(E&& err) const {
return BadExpectedAccess(static_cast<E&&>(err));
}
};
Error error_;
};
template <
class Error FOLLY_REQUIRES_TRAILING(IsEqualityComparable<Error>::value)>
inline bool operator==(
const Unexpected<Error>& lhs,
const Unexpected<Error>& rhs) {
return lhs.error() == rhs.error();
}
template <
class Error FOLLY_REQUIRES_TRAILING(IsEqualityComparable<Error>::value)>
inline bool operator!=(
const Unexpected<Error>& lhs,
const Unexpected<Error>& rhs) {
return !(lhs == rhs);
}
/**
* For constructing an Unexpected object from an error code. Unexpected objects
* are implicitly convertible to Expected object in the error state. Usage is
* as follows:
*
* enum class MyErrorCode { BAD_ERROR, WORSE_ERROR };
* Expected<int, MyErrorCode> myAPI() {
* int i = // ...;
* return i ? makeExpected<MyErrorCode>(i)
* : makeUnexpected(MyErrorCode::BAD_ERROR);
* }
*/
template <class Error>
constexpr Unexpected<typename std::decay<Error>::type> makeUnexpected(
Error&& err) {
return Unexpected<typename std::decay<Error>::type>{
static_cast<Error&&>(err)};
}
/**
* Expected - For holding a value or an error. Useful as an alternative to
* exceptions, for APIs where throwing on failure would be too expensive.
*
* Expected<Value, Error> is a variant over the types Value and Error.
*
* Expected does not offer support for references. Use
* Expected<std::reference_wrapper<T>, Error> if your API needs to return a
* reference or an error.
*
* Expected offers a continuation-based interface to reduce the boilerplate
* of checking error codes. The Expected::then member function takes a lambda
* that is to execute should the Expected object contain a value. The return
* value of the lambda is wrapped in an Expected and returned. If the lambda is
* not executed because the Expected contains an error, the error is returned
* immediately in a new Expected object.
*
* Expected<int, Error> funcTheFirst();
* Expected<std::string, Error> funcTheSecond() {
* return funcTheFirst().then([](int i) { return std::to_string(i); });
* }
*
* The above line of code could more verbosely written as:
*
* Expected<std::string, Error> funcTheSecond() {
* if (auto ex = funcTheFirst()) {
* return std::to_string(*ex);
* }
* return makeUnexpected(ex.error());
* }
*
* Continuations can chain, like:
*
* Expected<D, Error> maybeD = someFunc()
* .then([](A a){return B(a);})
* .then([](B b){return C(b);})
* .then([](C c){return D(c);});
*
* To avoid the redundant error checking that would happen if a call at the
* front of the chain returns an error, these call chains can be collaped into
* a single call to .then:
*
* Expected<D, Error> maybeD = someFunc()
* .then([](A a){return B(a);},
* [](B b){return C(b);},
* [](C c){return D(c);});
*
* The result of .then() is wrapped into Expected< ~, Error > if it isn't
* of that form already. Consider the following code:
*
* extern Expected<std::string, Error> readLineFromIO();
* extern Expected<int, Error> parseInt(std::string);
* extern int increment(int);
*
* Expected<int, Error> x = readLineFromIO().then(parseInt).then(increment);
*
* From the code above, we see that .then() works both with functions that
* return an Expected< ~, Error > (like parseInt) and with ones that return
* a plain value (like increment). In the case of parseInt, .then() returns
* the result of parseInt as-is. In the case of increment, it wraps the int
* that increment returns into an Expected< int, Error >.
*
* Sometimes when using a continuation you would prefer an exception to be
* thrown for a value-less Expected. For that you can use .thenOrThrow, as
* follows:
*
* B b = someFunc()
* .thenOrThrow([](A a){return B(a);});
*
* The above call to thenOrThrow will invoke the lambda if the Expected returned
* by someFunc() contains a value. Otherwise, it will throw an exception of type
* Unexpected<Error>::BadExpectedAccess. If you prefer it throw an exception of
* a different type, you can pass a second lambda to thenOrThrow:
*
* B b = someFunc()
* .thenOrThrow([](A a){return B(a);},
* [](Error e) {throw MyException(e);});
*
* Like C++17's std::variant, Expected offers the almost-never-empty guarantee;
* that is, an Expected<Value, Error> almost always contains either a Value or
* and Error. Partially-formed Expected objects occur when an assignment to
* an Expected object that would change the type of the contained object (Value-
* to-Error or vice versa) throws. Trying to access either the contained value
* or error object causes Expected to throw folly::BadExpectedAccess.
*
* Expected models OptionalPointee, so calling 'get_pointer(ex)' will return a
* pointer to nullptr if the 'ex' is in the error state, and a pointer to the
* value otherwise:
*
* Expected<int, Error> maybeInt = ...;
* if (int* v = get_pointer(maybeInt)) {
* cout << *v << endl;
* }
*/
template <class Value, class Error>
class Expected final : expected_detail::ExpectedStorage<Value, Error> {
template <class, class>
friend class Expected;
template <class, class, expected_detail::StorageType>
friend struct expected_detail::ExpectedStorage;
friend struct expected_detail::ExpectedHelper;
using Base = expected_detail::ExpectedStorage<Value, Error>;
using MakeBadExpectedAccess =
typename Unexpected<Error>::MakeBadExpectedAccess;
Base& base() & {
return *this;
}
const Base& base() const& {
return *this;
}
Base&& base() && {
return std::move(*this);
}
public:
using value_type = Value;
using error_type = Error;
using IsTriviallyCopyable = typename expected_detail::
StrictAllOf<IsTriviallyCopyable, Value, Error>::type;
template <class U>
using rebind = Expected<U, Error>;
static_assert(
!std::is_reference<Value>::value,
"Expected may not be used with reference types");
static_assert(
!std::is_abstract<Value>::value,
"Expected may not be used with abstract types");
/*
* Constructors
*/
template <class B = Base, class = decltype(B{})>
Expected() noexcept(noexcept(B{})) : Base{} {}
Expected(const Expected& that) = default;
Expected(Expected&& that) = default;
template <
class V,
class E FOLLY_REQUIRES_TRAILING(
!std::is_same<Expected<V, E>, Expected>::value &&
std::is_constructible<Value, V&&>::value &&
std::is_constructible<Error, E&&>::value)>
Expected(Expected<V, E> that) : Base{expected_detail::EmptyTag{}} {
*this = std::move(that);
}
FOLLY_REQUIRES(std::is_copy_constructible<Value>::value)
constexpr /* implicit */ Expected(const Value& val) noexcept(
noexcept(Value(val)))
: Base{expected_detail::ValueTag{}, val} {}
FOLLY_REQUIRES(std::is_move_constructible<Value>::value)
constexpr /* implicit */ Expected(Value&& val) noexcept(
noexcept(Value(std::move(val))))
: Base{expected_detail::ValueTag{}, std::move(val)} {}
template <class T FOLLY_REQUIRES_TRAILING(
std::is_convertible<T, Value>::value &&
!std::is_convertible<T, Error>::value)>
constexpr /* implicit */ Expected(T&& val) noexcept(
noexcept(Value(static_cast<T&&>(val))))
: Base{expected_detail::ValueTag{}, static_cast<T&&>(val)} {}
template <class... Ts FOLLY_REQUIRES_TRAILING(
std::is_constructible<Value, Ts&&...>::value)>
explicit constexpr Expected(in_place_t, Ts&&... ts) noexcept(
noexcept(Value(std::declval<Ts>()...)))
: Base{expected_detail::ValueTag{}, static_cast<Ts&&>(ts)...} {}
template <
class U,
class... Ts FOLLY_REQUIRES_TRAILING(
std::is_constructible<Value, std::initializer_list<U>&, Ts&&...>::
value)>
explicit constexpr Expected(
in_place_t,
std::initializer_list<U> il,
Ts&&... ts) noexcept(noexcept(Value(std::declval<Ts>()...)))
: Base{expected_detail::ValueTag{}, il, static_cast<Ts&&>(ts)...} {}
// If overload resolution selects one of these deleted functions, that
// means you need to use makeUnexpected
/* implicit */ Expected(const Error&) = delete;
/* implicit */ Expected(Error&&) = delete;
FOLLY_REQUIRES(std::is_copy_constructible<Error>::value)
constexpr Expected(unexpected_t, const Error& err) noexcept(
noexcept(Error(err)))
: Base{expected_detail::ErrorTag{}, err} {}
FOLLY_REQUIRES(std::is_move_constructible<Error>::value)
constexpr Expected(unexpected_t, Error&& err) noexcept(
noexcept(Error(std::move(err))))
: Base{expected_detail::ErrorTag{}, std::move(err)} {}
FOLLY_REQUIRES(std::is_copy_constructible<Error>::value)
constexpr /* implicit */ Expected(const Unexpected<Error>& err) noexcept(
noexcept(Error(err.error())))
: Base{expected_detail::ErrorTag{}, err.error()} {}
FOLLY_REQUIRES(std::is_move_constructible<Error>::value)
constexpr /* implicit */ Expected(Unexpected<Error>&& err) noexcept(
noexcept(Error(std::move(err.error()))))
: Base{expected_detail::ErrorTag{}, std::move(err.error())} {}
/*
* Assignment operators
*/
Expected& operator=(const Expected& that) = default;
Expected& operator=(Expected&& that) = default;
template <
class V,
class E FOLLY_REQUIRES_TRAILING(
!std::is_same<Expected<V, E>, Expected>::value &&
expected_detail::IsConvertible<V&&, Value>::value &&
expected_detail::IsConvertible<E&&, Error>::value)>
Expected& operator=(Expected<V, E> that) {
this->assign(std::move(that));
return *this;
}
FOLLY_REQUIRES(expected_detail::IsCopyable<Value>::value)
Expected& operator=(const Value& val) noexcept(
expected_detail::IsNothrowCopyable<Value>::value) {
this->assignValue(val);
return *this;
}
FOLLY_REQUIRES(expected_detail::IsMovable<Value>::value)
Expected& operator=(Value&& val) noexcept(
expected_detail::IsNothrowMovable<Value>::value) {
this->assignValue(std::move(val));
return *this;
}
template <class T FOLLY_REQUIRES_TRAILING(
std::is_convertible<T, Value>::value &&
!std::is_convertible<T, Error>::value)>