-
Notifications
You must be signed in to change notification settings - Fork 67
/
Future.swift
executable file
·1954 lines (1466 loc) · 72.2 KB
/
Future.swift
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
//
// Future.swift
// FutureKit
//
// Created by Michael Gray on 4/21/15.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public struct GLOBAL_PARMS {
// WOULD LOVE TO TURN THESE INTO COMPILE TIME PROPERTIES
// MAYBE VIA an Objective C Header file?
static let ALWAYS_ASYNC_DISPATCH_DEFAULT_TASKS = false
static let WRAP_DEPENDENT_BLOCKS_WITH_OBJC_EXCEPTION_HANDLING = false
static let CANCELLATION_CHAINING = true
static let STACK_CHECKING_PROPERTY = "FutureKit.immediate.TaskDepth"
static let CURRENT_EXECUTOR_PROPERTY = "FutureKit.Executor.Current"
static let STACK_CHECKING_MAX_DEPTH = 20
public static var LOCKING_STRATEGY : SynchronizationType = .PThreadMutex
}
public enum FutureKitError : ErrorType, Equatable {
case GenericError(String)
case ResultConversionError(String)
case CompletionConversionError(String)
case ContinueWithConversionError(String)
case ErrorForMultipleErrors(String,[ErrorType])
case ExceptionCaught(NSException,[NSObject:AnyObject]?)
public init(genericError : String) {
self = .GenericError(genericError)
}
public init(exception: NSException) {
var userInfo : [NSObject : AnyObject]
if (exception.userInfo != nil) {
userInfo = exception.userInfo!
}
else {
userInfo = [NSObject : AnyObject]()
}
userInfo["exception"] = NSException(name: exception.name, reason: exception.reason, userInfo: nil)
userInfo["callStackReturnAddresses"] = exception.callStackReturnAddresses
userInfo["callStackSymbols"] = exception.callStackSymbols
self = .ExceptionCaught(exception,userInfo)
}
}
public func == (l: FutureKitError, r: FutureKitError) -> Bool {
switch l {
case let .GenericError(lhs):
switch r {
case let .GenericError(rhs):
return (lhs == rhs)
default:
return false
}
case let .ResultConversionError(lhs):
switch r {
case let .ResultConversionError(rhs):
return (lhs == rhs)
default:
return false
}
case let .CompletionConversionError(lhs):
switch r {
case let .CompletionConversionError(rhs):
return (lhs == rhs)
default:
return false
}
case let .ContinueWithConversionError(lhs):
switch r {
case let .ContinueWithConversionError(rhs):
return (lhs == rhs)
default:
return false
}
case let .ErrorForMultipleErrors(lhs,_):
switch r {
case let .ErrorForMultipleErrors(rhs,_):
return (lhs == rhs)
default:
return false
}
case let .ExceptionCaught(lhs,_):
switch r {
case let .ExceptionCaught(rhs,_):
return (lhs.isEqual(rhs))
default:
return false
}
}
}
internal class CancellationTokenSource {
// we are going to keep a weak copy of each token we give out.
// as long as there
internal typealias CancellationTokenPtr = Weak<CancellationToken>
private var tokens : [CancellationTokenPtr] = []
// once we have triggered cancellation, we can't do it again
private var canBeCancelled = true
// this is to flag that someone has made a non-forced cancel request, but we are ignoring it due to other valid tokens
// if those tokens disappear, we will honor the cancel request then.
private var pendingCancelRequestActive = false
private var handler : CancellationHandler?
private var forcedCancellationHandler : CancellationHandler
init(forcedCancellationHandler h: CancellationHandler) {
self.forcedCancellationHandler = h
}
private var cancellationIsSupported : Bool {
return (self.handler != nil)
}
// add blocks that will be called as soon as we initiate cancelation
internal func addHandler(h : CancellationHandler) {
if !self.canBeCancelled {
return
}
if let oldhandler = self.handler
{
self.handler = { (options) in
oldhandler(options: options)
h(options: options)
}
}
else {
self.handler = h
}
}
internal func clear() {
self.handler = nil
self.canBeCancelled = false
self.tokens.removeAll()
}
internal func getNewToken(synchObject : SynchronizationProtocol, lockWhenAddingToken : Bool) -> CancellationToken {
if !self.canBeCancelled {
return self._createUntrackedToken()
}
let token = self._createTrackedToken(synchObject)
if (lockWhenAddingToken) {
synchObject.lockAndModify { () -> Void in
if self.canBeCancelled {
self.tokens.append(CancellationTokenPtr(token))
}
}
}
else {
self.tokens.append(CancellationTokenPtr(token))
}
return token
}
private func _createUntrackedToken() -> CancellationToken {
return CancellationToken(
onCancel: { [weak self] (options, token) -> Void in
self?._performCancel(options)
},
onDeinit:nil)
}
private func _createTrackedToken(synchObject : SynchronizationProtocol) -> CancellationToken {
return CancellationToken(
onCancel: { [weak self] (options, token) -> Void in
self?._cancelRequested(token, options, synchObject)
},
onDeinit:{ [weak self] (token) -> Void in
self?._clearInitializedToken(token,synchObject)
})
}
private func _removeToken(cancelingToken:CancellationToken) {
// so remove tokens that no longer exist and the requested token
self.tokens = self.tokens.filter { (tokenPtr) -> Bool in
if let token = tokenPtr.value {
return (token !== cancelingToken)
}
else {
return false
}
}
}
private func _performCancel(options : CancellationOptions) {
if self.canBeCancelled {
if (options.contains(.ForwardCancelRequestEvenIfThereAreOtherFuturesWaiting)) {
self.tokens.removeAll()
}
// there are no active tokens remaining, so allow the cancellation
if (self.tokens.count == 0) {
self.handler?(options: options)
self.canBeCancelled = false
self.handler = nil
}
else {
self.pendingCancelRequestActive = true
}
}
if options.contains(.ForceThisFutureToBeCancelledImmediately) {
self.forcedCancellationHandler(options: options)
}
}
private func _cancelRequested(cancelingToken:CancellationToken, _ options : CancellationOptions,_ synchObject : SynchronizationProtocol) {
synchObject.lockAndModify { () -> Void in
self._removeToken(cancelingToken)
self._performCancel(options)
}
}
private func _clearInitializedToken(token:CancellationToken,_ synchObject : SynchronizationProtocol) {
synchObject.lockAndModifySync { () -> Void in
self._removeToken(token)
if (self.pendingCancelRequestActive && self.tokens.count == 0) {
self.canBeCancelled = false
self.handler?(options: [])
}
}
}
}
public struct CancellationOptions : OptionSetType{
public let rawValue : Int
public init(rawValue:Int){ self.rawValue = rawValue}
/**
When the request is forwarded to another future, that future should cancel itself - even if there are other futures waiting for a result.
example:
let future: Future<NSData> = someFunction()
let firstChildofFuture = future.onComplete { (result) in
print("firstChildofFuture = \(result)")
}
let firstChildCancelToken = firstDependentFuture.getCancelToken()
let secondChildofFuture = future.onComplete { (result) in
print("secondChildofFuture result = \(result)")
}
firstChildCancelToken.cancel([.ForwardCancelRequestEvenIfThereAreOtherFuturesWaiting])
should result in `future` and `secondChildofFuture` being cancelled.
otherwise future may ignore the firstChildCancelToken request to cancel, because it is still trying to satisify secondChildofFuture
*/
static let ForwardCancelRequestEvenIfThereAreOtherFuturesWaiting = CancellationOptions(rawValue:1)
/**
If this future is dependent on the result of another future (via onComplete or .CompleteUsing(f))
than this cancellation request should NOT be forwarded to that future.
depending on the future's implementation, you may need include .ForceThisFutureToBeCancelledImmediately for cancellation to be successful
*/
static let DoNotForwardRequest = CancellationOptions(rawValue:2)
/**
this is allows you to 'short circuit' a Future's internal cancellation request logic.
The Cancellation request is still forwarded (unless .DoNotForwardRequest is also sent), but an unfinished Future will be forced into the .Cancelled state early.
*/
static let ForceThisFutureToBeCancelledImmediately = CancellationOptions(rawValue:4)
}
internal typealias CancellationHandler = ((options:CancellationOptions) -> Void)
public class CancellationToken {
final public func cancel(options : CancellationOptions = []) {
self.onCancel?(options:options,token:self)
self.onCancel = nil
}
public var cancelCanBeRequested : Bool {
return (self.onCancel != nil)
}
// private implementation details
deinit {
self.onDeinit?(token: self)
self.onDeinit = nil
}
internal typealias OnCancelHandler = ((options : CancellationOptions,token:CancellationToken) -> Void)
internal typealias OnDenitHandler = ((token:CancellationToken) -> Void)
private var onCancel : OnCancelHandler?
private var onDeinit : OnDenitHandler?
internal init(onCancel c:OnCancelHandler?, onDeinit d: OnDenitHandler?) {
self.onCancel = c
self.onDeinit = d
}
}
/**
All Futures use the protocol FutureProtocol
*/
public protocol FutureProtocol {
/**
convert this future of type `Future<T>` into another future type `Future<S>`
may fail to compile if T is not convertable into S using "`as!`"
works iff the following code works:
let t : T
let s = t as! S
example:
let f = Future<Int>(success:5)
let f2 : Future<Int32> = f.As()
assert(f2.result! == Int32(5))
you will need to formally declare the type of the new variable (ex: `f2`), in order for Swift to perform the correct conversion.
the following conversions should always work for any future
let fofany : Future<Any> = f.As()
let fofvoid: Future<Void> = f.As()
*/
func mapAs<S>() -> Future<S>
/**
convert Future<T> into another type Future<S?>.
WARNING: if 'T as! S' isn't legal, than all Success values may be converted to nil
example:
let f = Future<String>(success:"5")
let f2 : Future<[Int]?> = f.convertOptional()
assert(f2.result! == nil)
you will need to formally declare the type of the new variable (ex: `f2`), in order for Swift to perform the correct conversion.
*/
func mapAsOptional<S>() -> Future<S?>
var description: String { get }
}
/**
`Future<T>`
A Future is a swift generic class that let's you represent an object that will be returned at somepoint in the future. Usually from some asynchronous operation that may be running in a different thread/dispatch_queue or represent data that must be retrieved from a remote server somewhere.
*/
public class Future<T> : FutureProtocol{
public typealias ReturnType = T
internal typealias CompletionErrorHandler = Promise<T>.CompletionErrorHandler
internal typealias completion_block_type = ((FutureResult<T>) -> Void)
internal typealias cancellation_handler_type = (()-> Void)
private final var __callbacks : [completion_block_type]?
/**
this is used as the internal storage for `var completion`
it is not thread-safe to read this directly. use `var synchObject`
*/
private final var __result : FutureResult<T>?
// private final let lock = NSObject()
// Warning - reusing this lock for other purposes is dangerous when using LOCKING_STRATEGY.NSLock
// don't read or write values Future
/**
used to synchronize access to both __completion and __callbacks
type of synchronization can be configured via GLOBAL_PARMS.LOCKING_STRATEGY
*/
internal final var synchObject : SynchronizationProtocol = GLOBAL_PARMS.LOCKING_STRATEGY.lockObject()
/**
is executed used `cancel()` has been requested.
*/
internal func addRequestHandler(h : CancellationHandler) {
self.synchObject.lockAndModify { () -> Void in
self.cancellationSource.addHandler(h)
}
}
lazy var cancellationSource: CancellationTokenSource = {
return CancellationTokenSource(forcedCancellationHandler: { [weak self] (options) -> Void in
assert(options.contains(.ForceThisFutureToBeCancelledImmediately), "the forced cancellation handler is only supposed to run when the .ForceThisFutureToBeCancelledImmediately option is on")
self?.completeWith(.Cancelled)
})
}()
/**
returns: the current completion value of the Future
accessing this variable directly requires thread synchronization.
It is more efficient to examine completion values that are sent to an onComplete/onSuccess handler of a future than to examine it directly here.
type of synchronization used can be configured via GLOBAL_PARMS.LOCKING_STRATEGY
*/
public final var result : FutureResult<T>? {
get {
return self.synchObject.lockAndReadSync { () -> FutureResult<T>? in
return self.__result
}
}
}
/**
returns: the result of the Future iff the future has completed successfully. returns nil otherwise.
accessing this variable directly requires thread synchronization.
*/
public var value : T? {
get {
return self.result?.value
}
}
/**
returns: the error of the Future iff the future has completed with an Error. returns nil otherwise.
accessing this variable directly requires thread synchronization.
*/
public var error : ErrorType? {
get {
return self.result?.error
}
}
/**
is true if the Future supports cancellation requests using `cancel()`
May return true, even if the Future has already been completed, and cancellation is no longer possible.
It only informs the user that this type of future can be cancelled.
*/
public var cancellationIsSupported : Bool {
return self.synchObject.lockAndReadSync { () -> Bool in
return (self.cancellationSource.cancellationIsSupported)
}
}
/**
returns: true if the Future has completed with any completion value.
is NOT threadsafe
*/
private final var __isCompleted : Bool {
return (self.__result != nil)
}
/**
returns: true if the Future has completed with any completion value.
accessing this variable directly requires thread synchronization.
*/
public final var isCompleted : Bool {
return self.synchObject.lockAndReadSync { () -> Bool in
return self.__isCompleted
}
}
/**
You can't instanciate an incomplete Future directly. You must use a Promsie, or use an Executor with a block.
*/
internal init() {
}
// internal init(cancellationSource s: CancellationTokenSource) {
// self.cancellationSource = s
// }
/**
creates a completed Future.
*/
public init(completed:FutureResult<T>) { // returns an completed Task
self.__result = completed
}
/**
creates a completed Future with a completion == .Success(success)
*/
public init(success:T) { // returns an completed Task with result T
self.__result = .Success(success)
}
/**
creates a completed Future with a completion == .Error(failed)
*/
public init(failed:ErrorType) { // returns an completed Task that has Failed with this error
self.__result = .Fail(failed)
}
/**
creates a completed Future with a completion == .Error(FutureNSError(failWithErrorMessage))
*/
public init(failWithErrorMessage errorMessage: String) {
self.__result = FutureResult<T>(failWithErrorMessage:errorMessage)
}
/**
creates a completed Future with a completion == .Error(FutureNSError(exception))
*/
public init(exception:NSException) { // returns an completed Task that has Failed with this error
self.__result = FutureResult<T>(exception:exception)
}
/**
creates a completed Future with a completion == .Cancelled(cancelled)
*/
public init(cancelled:()) { // returns an completed Task that has Failed with this error
self.__result = .Cancelled
}
/**
creates a completed Future with a completion == .Cancelled(cancelled)
*/
public init(future f:Future<T>) { // returns an completed Task that has Failed with this error
self.completeWith(.CompleteUsing(f))
}
public convenience init(delay:NSTimeInterval, completeWith: Completion<T>) {
let executor: Executor = .Primary
let p = Promise<T>()
p.automaticallyCancelOnRequestCancel()
executor.executeAfterDelay(delay) { () -> Void in
p.complete(completeWith)
}
self.init(future:p.future)
}
public convenience init(afterDelay:NSTimeInterval, completeWith: Completion<T>) { // emits a .Success after delay
let executor: Executor = .Primary
let p = Promise<T>()
p.automaticallyCancelOnRequestCancel()
executor.executeAfterDelay(afterDelay) {
p.complete(completeWith)
}
self.init(future:p.future)
}
public convenience init(afterDelay:NSTimeInterval, success:T) { // emits a .Success after delay
let executor: Executor = .Primary
let p = Promise<T>()
p.automaticallyCancelOnRequestCancel()
executor.executeAfterDelay(afterDelay) {
p.completeWithSuccess(success)
}
self.init(future:p.future)
}
/**
Creates a future by executes block inside of an Executor, and when it's complete, sets the completion = .Success(block())
can only be used to a create a Future that should always succeed.
*/
public init(_ executor : Executor = .Immediate, block: () throws -> T) {
let block = executor.callbackBlockFor { () -> Void in
do {
let r = try block()
self.completeWith(.Success(r))
}
catch {
self.completeWith(.Fail(error))
}
}
block()
}
/**
Creates a future by executes block inside of an Executor, and when it's complete, sets the completion = block()
can be used to create a Future that may succeed or fail.
the block can return a value of .CompleteUsing(Future<T>) if it wants this Future to complete with the results of another future.
*/
public init(_ executor : Executor = .Immediate, block: () throws -> Completion<T>) {
executor.execute { () -> Void in
do {
self.completeWith(try block())
}
catch {
self.completeWith(.Fail(error))
}
}
}
/**
will complete the future and cause any registered callback blocks to be executed.
may execute asynchronously (depending on configured LOCKING_STRATEGY) and may return to the caller before it is finished executing.
type of synchronization used can be configured via GLOBAL_PARMS.LOCKING_STRATEGY
- parameter completion: the value to complete the Future with
*/
internal final func completeAndNotify(completion : Completion<T>) {
return self.completeWithBlocks(waitUntilDone: false,
completionBlock: { () -> Completion<T> in
completion
}, onCompletionError: nil)
}
/**
will complete the future and cause any registered callback blocks to be executed.
may execute asynchronously (depending on configured LOCKING_STRATEGY) and may return to the caller before it is finished executing.
if the Future has already been completed, the onCompletionError block will be executed. This block may be running in any queue (depending on the configure synchronization type).
type of synchronization used can be configured via GLOBAL_PARMS.LOCKING_STRATEGY
- parameter completion: the value to complete the Future with
- parameter onCompletionError: a block to execute if the Future has already been completed.
*/
internal final func completeAndNotify(completion : Completion<T>, onCompletionError : CompletionErrorHandler) {
self.completeWithBlocks(waitUntilDone: false, completionBlock: { () -> Completion<T> in
return completion
}, onCompletionError: onCompletionError)
}
/**
will complete the future and cause any registered callback blocks to be executed.
may block the current thread (depending on configured LOCKING_STRATEGY)
type of synchronization used can be configured via GLOBAL_PARMS.LOCKING_STRATEGY
- parameter completion: the value to complete the Future with
- returns: true if Future was successfully completed. Returns false if the Future has already been completed.
*/
internal final func completeAndNotifySync(completion : Completion<T>) -> Bool {
var ret = true
self.completeWithBlocks(waitUntilDone: true, completionBlock: { () -> Completion<T> in
return completion
}) { () -> Void in
ret = false
}
return ret
}
internal final func completeWithBlocks(
waitUntilDone wait:Bool = false,
completionBlock : () throws -> Completion<T>,
onCompletionError : (() -> Void)? = nil) {
typealias ModifyBlockReturnType = (callbacks:[completion_block_type]?,
result:FutureResult<T>?,
continueUsing:Future?)
self.synchObject.lockAndModify(waitUntilDone: wait, modifyBlock: { () -> ModifyBlockReturnType in
if let _ = self.__result {
// future was already complete!
return ModifyBlockReturnType(nil,nil,nil)
}
let c : Completion<T>
do {
c = try completionBlock()
}
catch {
c = .Fail(error)
}
if (c.isCompleteUsing) {
return ModifyBlockReturnType(callbacks:nil,result:nil,continueUsing:c.completeUsingFuture)
}
else {
let callbacks = self.__callbacks
self.__callbacks = nil
self.cancellationSource.clear()
self.__result = c.asResult()
return ModifyBlockReturnType(callbacks,self.__result,nil)
}
}, then:{ (modifyBlockReturned:ModifyBlockReturnType) -> Void in
if let callbacks = modifyBlockReturned.callbacks {
for callback in callbacks {
callback(modifyBlockReturned.result!)
}
}
if let f = modifyBlockReturned.continueUsing {
f.onComplete(.Immediate) { (nextComp) -> Void in
self.completeWith(nextComp.asCompletion())
}
let token = f.getCancelToken()
if token.cancelCanBeRequested {
self.addRequestHandler { (options : CancellationOptions) in
if !options.contains(.DoNotForwardRequest) {
token.cancel(options)
}
}
}
}
else if (modifyBlockReturned.result == nil) {
onCompletionError?()
}
})
}
/**
if completion is of type .CompleteUsing(f), than this will register an appropriate callback on f to complete this future iff f completes.
otherwise it will complete the future and cause any registered callback blocks to be executed.
may execute asynchronously (depending on configured LOCKING_STRATEGY) and may return to the caller before it is finished executing.
if the Future has already been completed, this function will do nothing. No error is generated.
- parameter completion: the value to complete the Future with
*/
internal func completeWith(completion : Completion<T>) {
return self.completeAndNotify(completion)
}
/**
if completion is of type .CompleteUsing(f), than this will register an appropriate callback on f to complete this future when f completes.
otherwise it will complete the future and cause any registered callback blocks to be executed.
may block the current thread
- parameter completion: the value to complete the Future with
- returns: true if Future was successfully completed. Returns false if the Future has already been completed.
*/
internal func completeWithSync(completion : Completion<T>) -> Bool {
return self.completeAndNotifySync(completion)
}
/**
if completion is of type .CompleteUsing(f), than this will register an appropriate callback on f to complete this future when f completes.
otherwise it will complete the future and cause any registered callback blocks to be executed.
will execute the block onCompletionError if the Future has already been completed. The onCompletionError block may execute inside any thread/queue, so care should be taken.
may execute asynchronously (depending on configured LOCKING_STRATEGY) and may return to the caller before it is finished executing.
- parameter completion: the value to complete the Future with
- parameter onCompletionError: a block to execute if the Future has already been completed.
*/
internal func completeWith(completion : Completion<T>, onCompletionError errorBlock: CompletionErrorHandler) {
return self.completeAndNotify(completion,onCompletionError: errorBlock)
}
/**
takes a user supplied block (usually from func onComplete()) and creates a Promise and a callback block that will complete the promise.
can add Objective-C Exception handling if GLOBAL_PARMS.WRAP_DEPENDENT_BLOCKS_WITH_OBJC_EXCEPTION_HANDLING is enabled.
- parameter forBlock: a user supplied block (via onComplete)
- returns: a tuple (promise,callbackblock) a new promise and a completion block that can be added to __callbacks
*/
internal final func createPromiseAndCallback<S>(forBlock: ((FutureResult<T>) throws -> Completion<S>)) -> (promise : Promise<S> , completionCallback :completion_block_type) {
let promise = Promise<S>()
let completionCallback : completion_block_type = {(comp) -> Void in
do {
let c = try forBlock(comp)
promise.complete(c)
}
catch {
promise.completeWithFail(error)
}
return
}
return (promise,completionCallback)
}
/**
takes a callback block and determines what to do with it based on the Future's current completion state.
If the Future has already been completed, than the callback block is executed.
If the Future is incomplete, it adds the callback block to the futures private var __callbacks
may execute asynchronously (depending on configured LOCKING_STRATEGY) and may return to the caller before it is finished executing.
- parameter callback: a callback block to be run if and when the future is complete
*/
private final func runThisCompletionBlockNowOrLater<S>(callback : completion_block_type,promise: Promise<S>) {
// lock my object, and either return the current completion value (if it's set)
// or add the block to the __callbacks if not.
self.synchObject.lockAndModifyAsync({ () -> FutureResult<T>? in
// we are done! return the current completion value.
if let c = self.__result {
return c
}
else
{
// we only allocate an array after getting the first __callbacks.
// cause we are hyper sensitive about not allocating extra stuff for temporary transient Futures.
switch self.__callbacks {
case let .Some(cb):
var newcb = cb
newcb.append(callback)
self.__callbacks = newcb
case .None:
self.__callbacks = [callback]
}
let t = self.cancellationSource.getNewToken(self.synchObject, lockWhenAddingToken: false)
promise.onRequestCancel(.Immediate) { (options) -> CancelRequestResponse<S> in
if !options.contains(.DoNotForwardRequest) {
t.cancel(options)
}
return .Continue
}
return nil
}
}, then: { (currentCompletionValue) -> Void in
// if we got a completion value, than we can execute the callback now.
if let c = currentCompletionValue {
callback(c)
}
})
}
/**
if we try to convert a future from type T to type T, just ignore the request.
the compile should automatically figure out which version of As() execute
*/
public final func As() -> Future<T> {
return self
}
/**
if we try to convert a future from type T to type T, just ignore the request.
the swift compiler can automatically figure out which version of mapAs() execute
*/
public final func mapAs() -> Future<T> {
return self
}
/**
convert this future of type `Future<T>` into another future type `Future<__Type>`
WARNING: if `T as! __Type` isn't legal, than your code may generate an exception.
works iff the following code works:
let t : T
let s = t as! __Type
example:
let f = Future<Int>(success:5)
let f2 : Future<Int32> = f.As()
assert(f2.result! == Int32(5))
you will need to formally declare the type of the new variable in order for Swift to perform the correct conversion.
the following conversions should always work for any future
let fofany : Future<Any> = f.As()
let fofvoid: Future<Void> = f.As()
- returns: a new Future of with the result type of __Type
*/
@available(*, deprecated=1.1, message="renamed to mapAs()")
public final func As<__Type>() -> Future<__Type> {
return self.mapAs()
}
/**
convert this future of type `Future<T>` into another future type `Future<__Type>`
WARNING: if `T as! __Type` isn't legal, than your code may generate an exception.
works iff the following code works:
let t : T
let s = t as! __Type
example:
let f = Future<Int>(success:5)
let f2 : Future<Int32> = f.As()
assert(f2.result! == Int32(5))
you will need to formally declare the type of the new variable in order for Swift to perform the correct conversion.
the following conversions should always work for any future
let fofany : Future<Any> = f.As()
let fofvoid: Future<Void> = f.As()
- returns: a new Future of with the result type of __Type
*/
public final func mapAs<__Type>() -> Future<__Type> {
return self.map(.Immediate) { (result) -> __Type in
return result as! __Type
}
}