summaryrefslogtreecommitdiffstats
path: root/src/corelib/thread/qfuture_impl.h
blob: 79fc6d9a017a9e34f12777290386e0cb322af7c4 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
// Copyright (C) 2020 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#ifndef QFUTURE_H
#error Do not include qfuture_impl.h directly
#endif

#if 0
#pragma qt_sync_skip_header_check
#pragma qt_sync_stop_processing
#endif

#include <QtCore/qglobal.h>
#include <QtCore/qfutureinterface.h>
#include <QtCore/qthreadpool.h>
#include <QtCore/qexception.h>
#include <QtCore/qpromise.h>

#include <memory>

QT_BEGIN_NAMESPACE

//
// forward declarations
//
template<class T>
class QFuture;
template<class T>
class QFutureInterface;
template<class T>
class QPromise;

namespace QtFuture {

enum class Launch { Sync, Async, Inherit };

template<class T>
struct WhenAnyResult
{
    qsizetype index = -1;
    QFuture<T> future;
};

// Deduction guide
template<class T>
WhenAnyResult(qsizetype, const QFuture<T> &) -> WhenAnyResult<T>;
}

namespace QtPrivate {

template<class T>
using EnableForVoid = std::enable_if_t<std::is_same_v<T, void>>;

template<class T>
using EnableForNonVoid = std::enable_if_t<!std::is_same_v<T, void>>;

template<typename F, typename Arg, typename Enable = void>
struct ResultTypeHelper
{
};

// The callable takes an argument of type Arg
template<typename F, typename Arg>
struct ResultTypeHelper<
        F, Arg, typename std::enable_if_t<!std::is_invocable_v<std::decay_t<F>, QFuture<Arg>>>>
{
    using ResultType = std::invoke_result_t<std::decay_t<F>, std::decay_t<Arg>>;
};

// The callable takes an argument of type QFuture<Arg>
template<class F, class Arg>
struct ResultTypeHelper<
        F, Arg, typename std::enable_if_t<std::is_invocable_v<std::decay_t<F>, QFuture<Arg>>>>
{
    using ResultType = std::invoke_result_t<std::decay_t<F>, QFuture<Arg>>;
};

// The callable takes an argument of type QFuture<void>
template<class F>
struct ResultTypeHelper<
        F, void, typename std::enable_if_t<std::is_invocable_v<std::decay_t<F>, QFuture<void>>>>
{
    using ResultType = std::invoke_result_t<std::decay_t<F>, QFuture<void>>;
};

// The callable doesn't take argument
template<class F>
struct ResultTypeHelper<
        F, void, typename std::enable_if_t<!std::is_invocable_v<std::decay_t<F>, QFuture<void>>>>
{
    using ResultType = std::invoke_result_t<std::decay_t<F>>;
};

// Helpers to remove QPrivateSignal argument from the list of arguments

template<class T, class Enable = void>
inline constexpr bool IsPrivateSignalArg = false;

template<class T>
inline constexpr bool IsPrivateSignalArg<T, typename std::enable_if_t<
        // finds injected-class-name, the 'class' avoids falling into the rules of [class.qual]/2:
        std::is_class_v<class T::QPrivateSignal>
    >> = true;

template<class Tuple, std::size_t... I>
auto cutTuple(Tuple &&t, std::index_sequence<I...>)
{
    return std::make_tuple(std::get<I>(t)...);
}

template<class Arg, class... Args>
auto createTuple(Arg &&arg, Args &&... args)
{
    using TupleType = std::tuple<std::decay_t<Arg>, std::decay_t<Args>...>;
    constexpr auto Size = sizeof...(Args); // One less than the size of all arguments
    if constexpr (QtPrivate::IsPrivateSignalArg<std::tuple_element_t<Size, TupleType>>) {
        if constexpr (Size == 1) {
            return std::forward<Arg>(arg);
        } else {
            return cutTuple(std::make_tuple(std::forward<Arg>(arg), std::forward<Args>(args)...),
                            std::make_index_sequence<Size>());
        }
    } else {
        return std::make_tuple(std::forward<Arg>(arg), std::forward<Args>(args)...);
    }
}

// Helpers to resolve argument types of callables.

template<class Arg, class... Args>
using FilterLastPrivateSignalArg =
        std::conditional_t<(sizeof...(Args) > 0),
                           std::invoke_result_t<decltype(createTuple<Arg, Args...>), Arg, Args...>,
                           std::conditional_t<IsPrivateSignalArg<Arg>, void, Arg>>;

template<typename...>
struct ArgsType;

template<typename Arg, typename... Args>
struct ArgsType<Arg, Args...>
{
    using First = Arg;
    using PromiseType = void;
    using IsPromise = std::false_type;
    static const bool HasExtraArgs = (sizeof...(Args) > 0);
    using AllArgs = FilterLastPrivateSignalArg<std::decay_t<Arg>, std::decay_t<Args>...>;

    template<class Class, class Callable>
    static const bool CanInvokeWithArgs = std::is_invocable_v<Callable, Class, Arg, Args...>;
};

template<typename Arg, typename... Args>
struct ArgsType<QPromise<Arg> &, Args...>
{
    using First = QPromise<Arg> &;
    using PromiseType = Arg;
    using IsPromise = std::true_type;
    static const bool HasExtraArgs = (sizeof...(Args) > 0);
    using AllArgs = FilterLastPrivateSignalArg<QPromise<Arg>, std::decay_t<Args>...>;

    template<class Class, class Callable>
    static const bool CanInvokeWithArgs = std::is_invocable_v<Callable, Class, QPromise<Arg> &, Args...>;
};

template<>
struct ArgsType<>
{
    using First = void;
    using PromiseType = void;
    using IsPromise = std::false_type;
    static const bool HasExtraArgs = false;
    using AllArgs = void;

    template<class Class, class Callable>
    static const bool CanInvokeWithArgs = std::is_invocable_v<Callable, Class>;
};

template<typename F>
struct ArgResolver : ArgResolver<decltype(&std::decay_t<F>::operator())>
{
};

template<typename F>
struct ArgResolver<std::reference_wrapper<F>> : ArgResolver<decltype(&std::decay_t<F>::operator())>
{
};

template<typename R, typename... Args>
struct ArgResolver<R(Args...)> : public ArgsType<Args...>
{
};

template<typename R, typename... Args>
struct ArgResolver<R (*)(Args...)> : public ArgsType<Args...>
{
};

template<typename R, typename... Args>
struct ArgResolver<R (*&)(Args...)> : public ArgsType<Args...>
{
};

template<typename R, typename... Args>
struct ArgResolver<R (* const)(Args...)> : public ArgsType<Args...>
{
};

template<typename R, typename... Args>
struct ArgResolver<R (&)(Args...)> : public ArgsType<Args...>
{
};

template<typename Class, typename R, typename... Args>
struct ArgResolver<R (Class::*)(Args...)> : public ArgsType<Args...>
{
};

template<typename Class, typename R, typename... Args>
struct ArgResolver<R (Class::*)(Args...) noexcept> : public ArgsType<Args...>
{
};

template<typename Class, typename R, typename... Args>
struct ArgResolver<R (Class::*)(Args...) const> : public ArgsType<Args...>
{
};

template<typename Class, typename R, typename... Args>
struct ArgResolver<R (Class::*)(Args...) const noexcept> : public ArgsType<Args...>
{
};

template<typename Class, typename R, typename... Args>
struct ArgResolver<R (Class::* const)(Args...) const> : public ArgsType<Args...>
{
};

template<typename Class, typename R, typename... Args>
struct ArgResolver<R (Class::* const)(Args...) const noexcept> : public ArgsType<Args...>
{
};

template<class Class, class Callable>
using EnableIfInvocable = std::enable_if_t<
        QtPrivate::ArgResolver<Callable>::template CanInvokeWithArgs<Class, Callable>>;

template<class T>
inline constexpr bool isQFutureV = false;

template<class T>
inline constexpr bool isQFutureV<QFuture<T>> = true;

template<class T>
using isQFuture = std::bool_constant<isQFutureV<T>>;

template<class T>
struct Future
{
};

template<class T>
struct Future<QFuture<T>>
{
    using type = T;
};

template<class... Args>
using NotEmpty = std::bool_constant<(sizeof...(Args) > 0)>;

template<class Sequence>
using IsRandomAccessible =
        std::is_convertible<typename std::iterator_traits<std::decay_t<decltype(
                                    std::begin(std::declval<Sequence>()))>>::iterator_category,
                            std::random_access_iterator_tag>;

template<class Sequence>
using HasInputIterator =
        std::is_convertible<typename std::iterator_traits<std::decay_t<decltype(
                                    std::begin(std::declval<Sequence>()))>>::iterator_category,
                            std::input_iterator_tag>;

template<class Iterator>
using IsForwardIterable =
        std::is_convertible<typename std::iterator_traits<Iterator>::iterator_category,
                            std::forward_iterator_tag>;

template<typename Function, typename ResultType, typename ParentResultType>
class Continuation
{
public:
    template<typename F = Function>
    Continuation(F &&func, const QFuture<ParentResultType> &f, QPromise<ResultType> &&p)
        : promise(std::move(p)), parentFuture(f), function(std::forward<F>(func))
    {
    }
    virtual ~Continuation() = default;

    bool execute();

    template<typename F = Function>
    static void create(F &&func, QFuture<ParentResultType> *f, QFutureInterface<ResultType> &fi,
                       QtFuture::Launch policy);

    template<typename F = Function>
    static void create(F &&func, QFuture<ParentResultType> *f, QFutureInterface<ResultType> &fi,
                       QThreadPool *pool);

    template<typename F = Function>
    static void create(F &&func, QFuture<ParentResultType> *f, QFutureInterface<ResultType> &fi,
                       QObject *context);

private:
    void fulfillPromiseWithResult();
    void fulfillVoidPromise();
    void fulfillPromiseWithVoidResult();

    template<class... Args>
    void fulfillPromise(Args &&... args);

protected:
    virtual void runImpl() = 0;

    void runFunction();

protected:
    QPromise<ResultType> promise;
    QFuture<ParentResultType> parentFuture;
    Function function;
};

template<typename Function, typename ResultType, typename ParentResultType>
class SyncContinuation final : public Continuation<Function, ResultType, ParentResultType>
{
public:
    template<typename F = Function>
    SyncContinuation(F &&func, const QFuture<ParentResultType> &f, QPromise<ResultType> &&p)
        : Continuation<Function, ResultType, ParentResultType>(std::forward<F>(func), f,
                                                               std::move(p))
    {
    }

    ~SyncContinuation() override = default;

private:
    void runImpl() override { this->runFunction(); }
};

template<typename Function, typename ResultType, typename ParentResultType>
class AsyncContinuation final : public QRunnable,
                                public Continuation<Function, ResultType, ParentResultType>
{
public:
    template<typename F = Function>
    AsyncContinuation(F &&func, const QFuture<ParentResultType> &f, QPromise<ResultType> &&p,
                      QThreadPool *pool = nullptr)
        : Continuation<Function, ResultType, ParentResultType>(std::forward<F>(func), f,
                                                               std::move(p)),
          threadPool(pool)
    {
    }

    ~AsyncContinuation() override = default;

private:
    void runImpl() override // from Continuation
    {
        QThreadPool *pool = threadPool ? threadPool : QThreadPool::globalInstance();
        pool->start(this);
    }

    void run() override // from QRunnable
    {
        this->runFunction();
    }

private:
    QThreadPool *threadPool;
};

#ifndef QT_NO_EXCEPTIONS

template<class Function, class ResultType>
class FailureHandler
{
public:
    template<typename F = Function>
    static void create(F &&function, QFuture<ResultType> *future,
                       const QFutureInterface<ResultType> &fi);

    template<typename F = Function>
    static void create(F &&function, QFuture<ResultType> *future, QFutureInterface<ResultType> &fi,
                       QObject *context);

    template<typename F = Function>
    FailureHandler(F &&func, const QFuture<ResultType> &f, QPromise<ResultType> &&p)
        : promise(std::move(p)), parentFuture(f), handler(std::forward<F>(func))
    {
    }

public:
    void run();

private:
    template<class ArgType>
    void handleException();
    void handleAllExceptions();

private:
    QPromise<ResultType> promise;
    QFuture<ResultType> parentFuture;
    Function handler;
};

#endif

template<typename Function, typename ResultType, typename ParentResultType>
void Continuation<Function, ResultType, ParentResultType>::runFunction()
{
    promise.start();

    Q_ASSERT(parentFuture.isFinished());

#ifndef QT_NO_EXCEPTIONS
    try {
#endif
        if constexpr (!std::is_void_v<ResultType>) {
            if constexpr (std::is_void_v<ParentResultType>) {
                fulfillPromiseWithVoidResult();
            } else if constexpr (std::is_invocable_v<Function, ParentResultType>) {
                fulfillPromiseWithResult();
            } else {
                // This assert normally should never fail, this is to make sure
                // that nothing unexpected happened.
                static_assert(std::is_invocable_v<Function, QFuture<ParentResultType>>,
                              "The continuation is not invocable with the provided arguments");
                fulfillPromise(parentFuture);
            }
        } else {
            if constexpr (std::is_void_v<ParentResultType>) {
                if constexpr (std::is_invocable_v<Function, QFuture<void>>)
                    function(parentFuture);
                else
                    function();
            } else if constexpr (std::is_invocable_v<Function, ParentResultType>) {
                fulfillVoidPromise();
            } else {
                // This assert normally should never fail, this is to make sure
                // that nothing unexpected happened.
                static_assert(std::is_invocable_v<Function, QFuture<ParentResultType>>,
                              "The continuation is not invocable with the provided arguments");
                function(parentFuture);
            }
        }
#ifndef QT_NO_EXCEPTIONS
    } catch (...) {
        promise.setException(std::current_exception());
    }
#endif
    promise.finish();
}

template<typename Function, typename ResultType, typename ParentResultType>
bool Continuation<Function, ResultType, ParentResultType>::execute()
{
    Q_ASSERT(parentFuture.isFinished());

    if (parentFuture.d.isChainCanceled()) {
#ifndef QT_NO_EXCEPTIONS
        if (parentFuture.d.hasException()) {
            // If the continuation doesn't take a QFuture argument, propagate the exception
            // to the caller, by reporting it. If the continuation takes a QFuture argument,
            // the user may want to catch the exception inside the continuation, to not
            // interrupt the continuation chain, so don't report anything yet.
            if constexpr (!std::is_invocable_v<std::decay_t<Function>, QFuture<ParentResultType>>) {
                promise.start();
                promise.setException(parentFuture.d.exceptionStore().exception());
                promise.finish();
                return false;
            }
        } else
#endif
        {
            promise.start();
            promise.future().cancel();
            promise.finish();
            return false;
        }
    }

    runImpl();
    return true;
}

// Workaround for keeping move-only lambdas inside std::function
template<class Function>
struct ContinuationWrapper
{
    ContinuationWrapper(Function &&f) : function(std::move(f)) { }
    ContinuationWrapper(const ContinuationWrapper &other)
        : function(std::move(const_cast<ContinuationWrapper &>(other).function))
    {
        Q_ASSERT_X(false, "QFuture", "Continuation shouldn't be copied");
    }
    ContinuationWrapper(ContinuationWrapper &&other) = default;
    ContinuationWrapper &operator=(ContinuationWrapper &&) = default;

    void operator()(const QFutureInterfaceBase &parentData) { function(parentData); }

private:
    Function function;
};

template<typename Function, typename ResultType, typename ParentResultType>
template<typename F>
void Continuation<Function, ResultType, ParentResultType>::create(F &&func,
                                                                  QFuture<ParentResultType> *f,
                                                                  QFutureInterface<ResultType> &fi,
                                                                  QtFuture::Launch policy)
{
    Q_ASSERT(f);

    QThreadPool *pool = nullptr;

    bool launchAsync = (policy == QtFuture::Launch::Async);
    if (policy == QtFuture::Launch::Inherit) {
        launchAsync = f->d.launchAsync();

        // If the parent future was using a custom thread pool, inherit it as well.
        if (launchAsync && f->d.threadPool()) {
            pool = f->d.threadPool();
            fi.setThreadPool(pool);
        }
    }

    fi.setLaunchAsync(launchAsync);

    auto continuation = [func = std::forward<F>(func), fi, promise_ = QPromise(fi), pool,
                         launchAsync](const QFutureInterfaceBase &parentData) mutable {
        const auto parent = QFutureInterface<ParentResultType>(parentData).future();
        Continuation<Function, ResultType, ParentResultType> *continuationJob = nullptr;
        if (launchAsync) {
            auto asyncJob = new AsyncContinuation<Function, ResultType, ParentResultType>(
                    std::forward<Function>(func), parent, std::move(promise_), pool);
            fi.setRunnable(asyncJob);
            continuationJob = asyncJob;
        } else {
            continuationJob = new SyncContinuation<Function, ResultType, ParentResultType>(
                    std::forward<Function>(func), parent, std::move(promise_));
        }

        bool isLaunched = continuationJob->execute();
        // If continuation is successfully launched, AsyncContinuation will be deleted
        // by the QThreadPool which has started it. Synchronous continuation will be
        // executed immediately, so it's safe to always delete it here.
        if (!(launchAsync && isLaunched)) {
            delete continuationJob;
            continuationJob = nullptr;
        }
    };
    f->d.setContinuation(ContinuationWrapper(std::move(continuation)), fi.d);
}

template<typename Function, typename ResultType, typename ParentResultType>
template<typename F>
void Continuation<Function, ResultType, ParentResultType>::create(F &&func,
                                                                  QFuture<ParentResultType> *f,
                                                                  QFutureInterface<ResultType> &fi,
                                                                  QThreadPool *pool)
{
    Q_ASSERT(f);

    fi.setLaunchAsync(true);
    fi.setThreadPool(pool);

    auto continuation = [func = std::forward<F>(func), promise_ = QPromise(fi),
                         pool](const QFutureInterfaceBase &parentData) mutable {
        const auto parent = QFutureInterface<ParentResultType>(parentData).future();
        auto continuationJob = new AsyncContinuation<Function, ResultType, ParentResultType>(
                std::forward<Function>(func), parent, std::move(promise_), pool);
        bool isLaunched = continuationJob->execute();
        // If continuation is successfully launched, AsyncContinuation will be deleted
        // by the QThreadPool which has started it.
        if (!isLaunched) {
            delete continuationJob;
            continuationJob = nullptr;
        }
    };
    f->d.setContinuation(ContinuationWrapper(std::move(continuation)), fi.d);
}

// defined in qfutureinterface.cpp:
Q_CORE_EXPORT void watchContinuationImpl(const QObject *context, QSlotObjectBase *slotObj,
                                         QFutureInterfaceBase &fi);
template <typename Continuation>
void watchContinuation(const QObject *context, Continuation &&c, QFutureInterfaceBase &fi)
{
    using Prototype = typename QtPrivate::Callable<Continuation>::Function;
    watchContinuationImpl(context,
                          QtPrivate::makeCallableObject<Prototype>(std::forward<Continuation>(c)),
                          fi);
}

template<typename Function, typename ResultType, typename ParentResultType>
template<typename F>
void Continuation<Function, ResultType, ParentResultType>::create(F &&func,
                                                                  QFuture<ParentResultType> *f,
                                                                  QFutureInterface<ResultType> &fi,
                                                                  QObject *context)
{
    Q_ASSERT(f);
    Q_ASSERT(context);

    // When the context object is destroyed, the signal-slot connection is broken and the
    // continuation callback is destroyed. The promise that is created in the capture list is
    // destroyed and, if it is not yet finished, cancelled.
    auto continuation = [func = std::forward<F>(func), parent = *f,
                         promise_ = QPromise(fi)]() mutable {
        SyncContinuation<Function, ResultType, ParentResultType> continuationJob(
                std::forward<Function>(func), parent, std::move(promise_));
        continuationJob.execute();
    };

    QtPrivate::watchContinuation(context, std::move(continuation), f->d);
}

template<typename Function, typename ResultType, typename ParentResultType>
void Continuation<Function, ResultType, ParentResultType>::fulfillPromiseWithResult()
{
    if constexpr (std::is_copy_constructible_v<ParentResultType>)
        fulfillPromise(parentFuture.result());
    else
        fulfillPromise(parentFuture.takeResult());
}

template<typename Function, typename ResultType, typename ParentResultType>
void Continuation<Function, ResultType, ParentResultType>::fulfillVoidPromise()
{
    if constexpr (std::is_copy_constructible_v<ParentResultType>)
        function(parentFuture.result());
    else
        function(parentFuture.takeResult());
}

template<typename Function, typename ResultType, typename ParentResultType>
void Continuation<Function, ResultType, ParentResultType>::fulfillPromiseWithVoidResult()
{
    if constexpr (std::is_invocable_v<Function, QFuture<void>>)
        fulfillPromise(parentFuture);
    else
        fulfillPromise();
}

template<typename Function, typename ResultType, typename ParentResultType>
template<class... Args>
void Continuation<Function, ResultType, ParentResultType>::fulfillPromise(Args &&... args)
{
    promise.addResult(std::invoke(function, std::forward<Args>(args)...));
}

template<class T>
void fulfillPromise(QPromise<T> &promise, QFuture<T> &future)
{
    if constexpr (!std::is_void_v<T>) {
        if constexpr (std::is_copy_constructible_v<T>)
            promise.addResult(future.result());
        else
            promise.addResult(future.takeResult());
    }
}

template<class T, class Function>
void fulfillPromise(QPromise<T> &promise, Function &&handler)
{
    if constexpr (std::is_void_v<T>)
        handler();
    else
        promise.addResult(handler());
}

#ifndef QT_NO_EXCEPTIONS

template<class Function, class ResultType>
template<class F>
void FailureHandler<Function, ResultType>::create(F &&function, QFuture<ResultType> *future,
                                                  const QFutureInterface<ResultType> &fi)
{
    Q_ASSERT(future);

    auto failureContinuation = [function = std::forward<F>(function), promise_ = QPromise(fi)](
                                       const QFutureInterfaceBase &parentData) mutable {
        const auto parent = QFutureInterface<ResultType>(parentData).future();
        FailureHandler<Function, ResultType> failureHandler(std::forward<Function>(function),
                                                            parent, std::move(promise_));
        failureHandler.run();
    };

    future->d.setContinuation(ContinuationWrapper(std::move(failureContinuation)));
}

template<class Function, class ResultType>
template<class F>
void FailureHandler<Function, ResultType>::create(F &&function, QFuture<ResultType> *future,
                                                  QFutureInterface<ResultType> &fi,
                                                  QObject *context)
{
    Q_ASSERT(future);
    Q_ASSERT(context);
    auto failureContinuation = [function = std::forward<F>(function),
                                parent = *future, promise_ = QPromise(fi)]() mutable {
        FailureHandler<Function, ResultType> failureHandler(
                std::forward<Function>(function), parent, std::move(promise_));
        failureHandler.run();
    };

    QtPrivate::watchContinuation(context, std::move(failureContinuation), future->d);
}

template<class Function, class ResultType>
void FailureHandler<Function, ResultType>::run()
{
    Q_ASSERT(parentFuture.isFinished());

    promise.start();

    if (parentFuture.d.hasException()) {
        using ArgType = typename QtPrivate::ArgResolver<Function>::First;
        if constexpr (std::is_void_v<ArgType>) {
            handleAllExceptions();
        } else {
            handleException<ArgType>();
        }
    } else if (parentFuture.d.isChainCanceled()) {
        promise.future().cancel();
    } else {
        QtPrivate::fulfillPromise(promise, parentFuture);
    }
    promise.finish();
}

template<class Function, class ResultType>
template<class ArgType>
void FailureHandler<Function, ResultType>::handleException()
{
    try {
        Q_ASSERT(parentFuture.d.hasException());
        parentFuture.d.exceptionStore().rethrowException();
    } catch (const ArgType &e) {
        try {
            // Handle exceptions matching with the handler's argument type
            if constexpr (std::is_void_v<ResultType>)
                handler(e);
            else
                promise.addResult(handler(e));
        } catch (...) {
            promise.setException(std::current_exception());
        }
    } catch (...) {
        // Exception doesn't match with handler's argument type, propagate
        // the exception to be handled later.
        promise.setException(std::current_exception());
    }
}

template<class Function, class ResultType>
void FailureHandler<Function, ResultType>::handleAllExceptions()
{
    try {
        Q_ASSERT(parentFuture.d.hasException());
        parentFuture.d.exceptionStore().rethrowException();
    } catch (...) {
        try {
            QtPrivate::fulfillPromise(promise, std::forward<Function>(handler));
        } catch (...) {
            promise.setException(std::current_exception());
        }
    }
}

#endif // QT_NO_EXCEPTIONS

template<class Function, class ResultType>
class CanceledHandler
{
public:
    template<class F = Function>
    static void create(F &&handler, QFuture<ResultType> *future, QFutureInterface<ResultType> &fi)
    {
        Q_ASSERT(future);

        auto canceledContinuation = [promise = QPromise(fi), handler = std::forward<F>(handler)](
                                            const QFutureInterfaceBase &parentData) mutable {
            auto parentFuture = QFutureInterface<ResultType>(parentData).future();
            run(std::forward<F>(handler), parentFuture, std::move(promise));
        };
        future->d.setContinuation(ContinuationWrapper(std::move(canceledContinuation)));
    }

    template<class F = Function>
    static void create(F &&handler, QFuture<ResultType> *future, QFutureInterface<ResultType> &fi,
                       QObject *context)
    {
        Q_ASSERT(future);
        Q_ASSERT(context);
        auto canceledContinuation = [handler = std::forward<F>(handler),
                                     parentFuture = *future, promise = QPromise(fi)]() mutable {
            run(std::forward<F>(handler), parentFuture, std::move(promise));
        };

        QtPrivate::watchContinuation(context, std::move(canceledContinuation), future->d);
    }

    template<class F = Function>
    static void run(F &&handler, QFuture<ResultType> &parentFuture, QPromise<ResultType> &&promise)
    {
        promise.start();

        if (parentFuture.isCanceled()) {
#ifndef QT_NO_EXCEPTIONS
            if (parentFuture.d.hasException()) {
                // Propagate the exception to the result future
                promise.setException(parentFuture.d.exceptionStore().exception());
            } else {
                try {
#endif
                    QtPrivate::fulfillPromise(promise, std::forward<F>(handler));
#ifndef QT_NO_EXCEPTIONS
                } catch (...) {
                    promise.setException(std::current_exception());
                }
            }
#endif
        } else {
            QtPrivate::fulfillPromise(promise, parentFuture);
        }

        promise.finish();
    }
};

struct UnwrapHandler
{
    template<class T>
    static auto unwrapImpl(T *outer)
    {
        Q_ASSERT(outer);

        using ResultType = typename QtPrivate::Future<std::decay_t<T>>::type;
        using NestedType = typename QtPrivate::Future<ResultType>::type;
        QFutureInterface<NestedType> promise(QFutureInterfaceBase::State::Pending);

        outer->then([promise](const QFuture<ResultType> &outerFuture) mutable {
            // We use the .then([](QFuture<ResultType> outerFuture) {...}) version
            // (where outerFuture == *outer), to propagate the exception if the
            // outer future has failed.
            Q_ASSERT(outerFuture.isFinished());
#ifndef QT_NO_EXCEPTIONS
            if (outerFuture.d.hasException()) {
                promise.reportStarted();
                promise.reportException(outerFuture.d.exceptionStore().exception());
                promise.reportFinished();
                return;
            }
#endif

            promise.reportStarted();
            ResultType nestedFuture = outerFuture.result();

            nestedFuture.then([promise] (const QFuture<NestedType> &nested) mutable {
#ifndef QT_NO_EXCEPTIONS
                if (nested.d.hasException()) {
                    promise.reportException(nested.d.exceptionStore().exception());
                } else
#endif
                {
                    if constexpr (!std::is_void_v<NestedType>)
                        promise.reportResults(nested.results());
                }
                promise.reportFinished();
            }).onCanceled([promise] () mutable {
                promise.reportCanceled();
                promise.reportFinished();
            });
        }).onCanceled([promise]() mutable {
            // propagate the cancellation of the outer future
            promise.reportStarted();
            promise.reportCanceled();
            promise.reportFinished();
        });
        return promise.future();
    }
};

template<typename ValueType>
QFuture<ValueType> makeReadyRangeFutureImpl(const QList<ValueType> &values)
{
    QFutureInterface<ValueType> promise;
    promise.reportStarted();
    promise.reportResults(values);
    promise.reportFinished();
    return promise.future();
}

} // namespace QtPrivate

namespace QtFuture {

template<class Signal>
using ArgsType = typename QtPrivate::ArgResolver<Signal>::AllArgs;

template<class Sender, class Signal, typename = QtPrivate::EnableIfInvocable<Sender, Signal>>
static QFuture<ArgsType<Signal>> connect(Sender *sender, Signal signal)
{
    using ArgsType = ArgsType<Signal>;
    QFutureInterface<ArgsType> promise;
    promise.reportStarted();
    if (!sender) {
        promise.reportCanceled();
        promise.reportFinished();
        return promise.future();
    }

    using Connections = std::pair<QMetaObject::Connection, QMetaObject::Connection>;
    auto connections = std::make_shared<Connections>();

    if constexpr (std::is_void_v<ArgsType>) {
        connections->first =
                QObject::connect(sender, signal, sender, [promise, connections]() mutable {
                    QObject::disconnect(connections->first);
                    QObject::disconnect(connections->second);
                    promise.reportFinished();
                });
    } else if constexpr (QtPrivate::ArgResolver<Signal>::HasExtraArgs) {
        connections->first = QObject::connect(sender, signal, sender,
                                              [promise, connections](auto... values) mutable {
                                                  QObject::disconnect(connections->first);
                                                  QObject::disconnect(connections->second);
                                                  promise.reportResult(QtPrivate::createTuple(
                                                          std::move(values)...));
                                                  promise.reportFinished();
                                              });
    } else {
        connections->first = QObject::connect(sender, signal, sender,
                                              [promise, connections](ArgsType value) mutable {
                                                  QObject::disconnect(connections->first);
                                                  QObject::disconnect(connections->second);
                                                  promise.reportResult(value);
                                                  promise.reportFinished();
                                              });
    }

    if (!connections->first) {
        promise.reportCanceled();
        promise.reportFinished();
        return promise.future();
    }

    connections->second =
            QObject::connect(sender, &QObject::destroyed, sender, [promise, connections]() mutable {
                QObject::disconnect(connections->first);
                QObject::disconnect(connections->second);
                promise.reportCanceled();
                promise.reportFinished();
            });

    return promise.future();
}

template<typename Container>
using if_container_with_input_iterators =
        std::enable_if_t<QtPrivate::HasInputIterator<Container>::value, bool>;

template<typename Container>
using ContainedType =
        typename std::iterator_traits<decltype(
                    std::cbegin(std::declval<Container&>()))>::value_type;

template<typename Container, if_container_with_input_iterators<Container> = true>
static QFuture<ContainedType<Container>> makeReadyRangeFuture(Container &&container)
{
    // handle QList<T> separately, because reportResults() takes a QList
    // as an input
    using ValueType = ContainedType<Container>;
    if constexpr (std::is_convertible_v<q20::remove_cvref_t<Container>, QList<ValueType>>) {
        return QtPrivate::makeReadyRangeFutureImpl(container);
    } else {
        return QtPrivate::makeReadyRangeFutureImpl(QList<ValueType>{std::cbegin(container),
                                                                    std::cend(container)});
    }
}

template<typename ValueType>
static QFuture<ValueType> makeReadyRangeFuture(std::initializer_list<ValueType> values)
{
    return QtPrivate::makeReadyRangeFutureImpl(QList<ValueType>{values});
}

template<typename T>
static QFuture<std::decay_t<T>> makeReadyValueFuture(T &&value)
{
    QFutureInterface<std::decay_t<T>> promise;
    promise.reportStarted();
    promise.reportResult(std::forward<T>(value));
    promise.reportFinished();

    return promise.future();
}

Q_CORE_EXPORT QFuture<void> makeReadyVoidFuture(); // implemented in qfutureinterface.cpp

#if QT_DEPRECATED_SINCE(6, 10)
template<typename T, typename = QtPrivate::EnableForNonVoid<T>>
QT_DEPRECATED_VERSION_X(6, 10, "Use makeReadyValueFuture() instead.")
static QFuture<std::decay_t<T>> makeReadyFuture(T &&value)
{
    return makeReadyValueFuture(std::forward<T>(value));
}

// the void specialization is moved to the end of qfuture.h, because it now
// uses makeReadyVoidFuture() and required QFuture<void> to be defined.

template<typename T>
QT_DEPRECATED_VERSION_X(6, 10, "Use makeReadyRangeFuture() instead.")
static QFuture<T> makeReadyFuture(const QList<T> &values)
{
    return makeReadyRangeFuture(values);
}
#endif // QT_DEPRECATED_SINCE(6, 10)

#ifndef QT_NO_EXCEPTIONS

template<typename T = void>
static QFuture<T> makeExceptionalFuture(std::exception_ptr exception)
{
    QFutureInterface<T> promise;
    promise.reportStarted();
    promise.reportException(exception);
    promise.reportFinished();

    return promise.future();
}

template<typename T = void>
static QFuture<T> makeExceptionalFuture(const QException &exception)
{
    try {
        exception.raise();
    } catch (...) {
        return makeExceptionalFuture<T>(std::current_exception());
    }
    Q_UNREACHABLE();
}

#endif // QT_NO_EXCEPTIONS

} // namespace QtFuture

namespace QtPrivate {

template<typename ResultFutures>
struct WhenAllContext
{
    using ValueType = typename ResultFutures::value_type;

    explicit WhenAllContext(qsizetype size) : remaining(size) {}

    template<typename T = ValueType>
    void checkForCompletion(qsizetype index, T &&future)
    {
        futures[index] = std::forward<T>(future);
        const auto oldRemaining = remaining.fetchAndSubRelaxed(1);
        Q_ASSERT(oldRemaining > 0);
        if (oldRemaining <= 1) { // that was the last one
            promise.addResult(futures);
            promise.finish();
        }
    }

    QAtomicInteger<qsizetype> remaining;
    QPromise<ResultFutures> promise;
    ResultFutures futures;
};

template<typename ResultType>
struct WhenAnyContext
{
    using ValueType = ResultType;

    template<typename T = ResultType, typename = EnableForNonVoid<T>>
    void checkForCompletion(qsizetype, T &&result)
    {
        if (!ready.fetchAndStoreRelaxed(true)) {
            promise.addResult(std::forward<T>(result));
            promise.finish();
        }
    }

    QAtomicInt ready = false;
    QPromise<ResultType> promise;
};

template<qsizetype Index, typename ContextType, typename... Ts>
void addCompletionHandlersImpl(const std::shared_ptr<ContextType> &context,
                               const std::tuple<Ts...> &t)
{
    auto future = std::get<Index>(t);
    using ResultType = typename ContextType::ValueType;
    // Need context=context so that the compiler does not infer the captured variable's type as 'const'
    future.then([context=context](const std::tuple_element_t<Index, std::tuple<Ts...>> &f) {
        context->checkForCompletion(Index, ResultType { std::in_place_index<Index>, f });
    }).onCanceled([context=context, future]() {
        context->checkForCompletion(Index, ResultType { std::in_place_index<Index>, future });
    });

    if constexpr (Index != 0)
        addCompletionHandlersImpl<Index - 1, ContextType, Ts...>(context, t);
}

template<typename ContextType, typename... Ts>
void addCompletionHandlers(const std::shared_ptr<ContextType> &context, const std::tuple<Ts...> &t)
{
    constexpr qsizetype size = std::tuple_size<std::tuple<Ts...>>::value;
    addCompletionHandlersImpl<size - 1, ContextType, Ts...>(context, t);
}

template<typename OutputSequence, typename InputIt, typename ValueType>
QFuture<OutputSequence> whenAllImpl(InputIt first, InputIt last)
{
    const qsizetype size = std::distance(first, last);
    if (size == 0)
        return QtFuture::makeReadyValueFuture(OutputSequence());

    const auto context = std::make_shared<QtPrivate::WhenAllContext<OutputSequence>>(size);
    context->futures.resize(size);
    context->promise.start();

    qsizetype idx = 0;
    for (auto it = first; it != last; ++it, ++idx) {
        // Need context=context so that the compiler does not infer the captured variable's type as 'const'
        it->then([context=context, idx](const ValueType &f) {
            context->checkForCompletion(idx, f);
        }).onCanceled([context=context, idx, f = *it] {
            context->checkForCompletion(idx, f);
        });
    }
    return context->promise.future();
}

template<typename OutputSequence, typename... Futures>
QFuture<OutputSequence> whenAllImpl(Futures &&... futures)
{
    constexpr qsizetype size = sizeof...(Futures);
    const auto context = std::make_shared<QtPrivate::WhenAllContext<OutputSequence>>(size);
    context->futures.resize(size);
    context->promise.start();

    QtPrivate::addCompletionHandlers(context, std::make_tuple(std::forward<Futures>(futures)...));

    return context->promise.future();
}

template<typename InputIt, typename ValueType>
QFuture<QtFuture::WhenAnyResult<typename Future<ValueType>::type>> whenAnyImpl(InputIt first,
                                                                               InputIt last)
{
    using PackagedType = typename Future<ValueType>::type;
    using ResultType = QtFuture::WhenAnyResult<PackagedType>;

    const qsizetype size = std::distance(first, last);
    if (size == 0) {
        return QtFuture::makeReadyValueFuture(
                QtFuture::WhenAnyResult { qsizetype(-1), QFuture<PackagedType>() });
    }

    const auto context = std::make_shared<QtPrivate::WhenAnyContext<ResultType>>();
    context->promise.start();

    qsizetype idx = 0;
    for (auto it = first; it != last; ++it, ++idx) {
        // Need context=context so that the compiler does not infer the captured variable's type as 'const'
        it->then([context=context, idx](const ValueType &f) {
            context->checkForCompletion(idx, QtFuture::WhenAnyResult { idx, f });
        }).onCanceled([context=context, idx, f = *it] {
            context->checkForCompletion(idx, QtFuture::WhenAnyResult { idx, f });
        });
    }
    return context->promise.future();
}

template<typename... Futures>
QFuture<std::variant<std::decay_t<Futures>...>> whenAnyImpl(Futures &&... futures)
{
    using ResultType = std::variant<std::decay_t<Futures>...>;

    const auto context = std::make_shared<QtPrivate::WhenAnyContext<ResultType>>();
    context->promise.start();

    QtPrivate::addCompletionHandlers(context, std::make_tuple(std::forward<Futures>(futures)...));

    return context->promise.future();
}

} // namespace QtPrivate

QT_END_NAMESPACE