summaryrefslogtreecommitdiff
path: root/swift/src/Ice/Proxy.swift
blob: c46cd965807d894a4e52144d72ba1fa6c029d75e (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
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
//
// Copyright (c) ZeroC, Inc. All rights reserved.
//

import Foundation
import IceImpl
import PromiseKit

/// The base protocol for all Ice proxies.
public protocol ObjectPrx: CustomStringConvertible, AnyObject {
    /// Returns the communicator that created this proxy.
    ///
    /// - returns: `Ice.Communicator` - The communicator that created this proxy.
    func ice_getCommunicator() -> Communicator

    /// Returns the identity embedded in this proxy.
    ///
    /// - returns: `Ice.Identity` - The identity of the target object.
    func ice_getIdentity() -> Identity

    /// Creates a new proxy that is identical to this proxy, except for the identity.
    ///
    /// - parameter _: `Ice.Identity` - The identity for the new proxy.
    ///
    /// - returns: A proxy with the new identity.
    func ice_identity(_ id: Identity) -> Self

    /// Returns the per-proxy context for this proxy.
    ///
    /// - returns: `Ice.Context` - The per-proxy context.
    func ice_getContext() -> Context

    /// Creates a new proxy that is identical to this proxy, except for the per-proxy context.
    ///
    /// - parameter newContext: `Ice.Context` - The context for the new proxy.
    ///
    /// - returns: The proxy with the new per-proxy context.
    func ice_context(_ context: Context) -> Self

    /// Returns the facet for this proxy.
    ///
    /// - returns: `String` - The facet for this proxy. If the proxy uses the default facet,
    ///   the return value is the empty string.
    func ice_getFacet() -> String

    /// Creates a new proxy that is identical to this proxy, except for the facet.
    ///
    /// - parameter _: `String` - The facet for the new proxy.
    ///
    /// - returns: `Ice.ObjectPrx` - The proxy with the new facet.
    func ice_facet(_ facet: String) -> ObjectPrx

    /// Returns the adapter ID for this proxy.
    ///
    /// - returns: `String` - The adapter ID. If the proxy does not have an adapter ID, the return value is the
    ///   empty string.
    func ice_getAdapterId() -> String

    /// Creates a new proxy that is identical to this proxy, except for the adapter ID.
    ///
    /// - parameter _: `String` - The adapter ID for the new proxy.
    ///
    /// - returns: The proxy with the new adapter ID.
    func ice_adapterId(_ id: String) -> Self

    /// Returns the endpoints used by this proxy.
    ///
    /// - returns: `EndpointSeq` - The endpoints used by this proxy.
    func ice_getEndpoints() -> EndpointSeq

    /// Creates a new proxy that is identical to this proxy, except for the endpoints.
    ///
    /// - parameter _: `EndpointSeq` - The endpoints for the new proxy.
    ///
    /// - returns: The proxy with the new endpoints.
    func ice_endpoints(_ endpoints: EndpointSeq) -> Self

    /// Returns the locator cache timeout of this proxy.
    ///
    /// - returns: `Int32` - The locator cache timeout value (in seconds).
    func ice_getLocatorCacheTimeout() -> Int32

    /// Creates a new proxy that is identical to this proxy, except for the locator cache timeout.
    ///
    /// - parameter _: `Int32` - The new locator cache timeout (in seconds).
    ///
    /// - returns: A new proxy with the specified cache timeout.
    func ice_locatorCacheTimeout(_ timeout: Int32) -> Self

    /// Returns the invocation timeout of this proxy.
    ///
    /// - returns: `Int32` - The invocation timeout value (in seconds).
    func ice_getInvocationTimeout() -> Int32

    /// Creates a new proxy that is identical to this proxy, except for the invocation timeout.
    ///
    /// - parameter _: `Int32` - The new invocation timeout (in seconds).
    ///
    /// - returns: A new proxy with the specified invocation timeout.
    func ice_invocationTimeout(_ timeout: Int32) -> Self

    /// Returns the connection id of this proxy.
    ///
    /// returns: `String` - The connection id.
    func ice_getConnectionId() -> String

    /// Creates a new proxy that is identical to this proxy, except for its connection ID.
    ///
    /// - parameter _: `String` - The connection ID for the new proxy. An empty string removes the
    ///   connection ID.
    ///
    /// - returns: A new proxy with the specified connection ID.
    func ice_connectionId(_ id: String) -> Self

    /// Returns whether this proxy caches connections.
    ///
    /// - returns: `Bool` - True if this proxy caches connections; false, otherwise.
    func ice_isConnectionCached() -> Bool

    /// Creates a new proxy that is identical to this proxy, except for connection caching.
    ///
    /// - parameter _: `Bool` - True if the new proxy should cache connections; false, otherwise.
    ///
    /// - returns: The new proxy with the specified caching policy.
    func ice_connectionCached(_ cached: Bool) -> Self

    /// Returns how this proxy selects endpoints (randomly or ordered).
    ///
    /// - returns: `Ice.EndpointSelectionType` - The endpoint selection policy.
    func ice_getEndpointSelection() -> EndpointSelectionType

    /// Creates a new proxy that is identical to this proxy, except for the endpoint selection policy.
    ///
    /// - parameter _: `Ice.EndpointSelectionType` - The new endpoint selection policy.
    ///
    /// - returns: The new proxy with the specified endpoint selection policy.
    func ice_endpointSelection(_ type: EndpointSelectionType) -> Self

    /// Returns the encoding version used to marshal requests parameters.
    ///
    /// - returns: `Ice.EncodingVersion` - The encoding version.
    func ice_getEncodingVersion() -> EncodingVersion

    /// Creates a new proxy that is identical to this proxy, except for the encoding used to marshal
    /// parameters.
    ///
    /// - parameter _: `Ice.EncodingVersion` - The encoding version to use to marshal requests parameters.
    ///
    /// - returns: The new proxy with the specified encoding version.
    func ice_encodingVersion(_ encoding: EncodingVersion) -> Self

    /// Returns the router for this proxy.
    ///
    /// - returns: `Ice.RouterPrx?` - The router for the proxy. If no router is configured for the proxy,
    ///   the return value is nil.
    func ice_getRouter() -> RouterPrx?

    /// Creates a new proxy that is identical to this proxy, except for the router.
    ///
    /// - parameter router: `Ice.RouterPrx?` - The router for the new proxy.
    ///
    /// - returns: The new proxy with the specified router.
    func ice_router(_ router: RouterPrx?) -> Self

    /// Returns the locator for this proxy.
    ///
    /// - returns: `Ice.LocatorPrx?` - The locator for this proxy. If no locator is configured, the
    ///   return value is nil.
    func ice_getLocator() -> LocatorPrx?

    /// Creates a new proxy that is identical to this proxy, except for the locator.
    ///
    /// - parameter _: `Ice.LocatorPrx` The locator for the new proxy.
    ///
    /// - returns: The new proxy with the specified locator.
    func ice_locator(_ locator: LocatorPrx?) -> Self

    /// Returns whether this proxy communicates only via secure endpoints.
    ///
    /// - returns: `Bool` - True if this proxy communicates only via secure endpoints; false, otherwise.
    func ice_isSecure() -> Bool

    /// Creates a new proxy that is identical to this proxy, except for how it selects endpoints.
    ///
    /// - parameter _: `Bool` - If true only endpoints that use a secure transport are used by the new proxy.
    ///   otherwise the returned proxy uses both secure and insecure endpoints.
    ///
    /// - returns: The new proxy with the specified selection policy.
    func ice_secure(_ secure: Bool) -> Self

    /// Returns whether this proxy prefers secure endpoints.
    ///
    /// - returns: `Bool` - True if the proxy always attempts to invoke via secure endpoints before it
    ///   attempts to use insecure endpoints; false, otherwise.
    func ice_isPreferSecure() -> Bool

    /// Creates a new proxy that is identical to this proxy, except for its endpoint selection policy.
    ///
    /// - parameter _: `Bool` - If true, the new proxy will use secure endpoints for invocations
    ///   and only use insecure endpoints if an invocation cannot be made via secure endpoints. Otherwise
    ///   the proxy prefers insecure endpoints to secure ones.
    ///
    /// - returns: The new proxy with the new endpoint selection policy.
    func ice_preferSecure(_ preferSecure: Bool) -> Self

    /// Returns whether this proxy uses twoway invocations.
    ///
    /// - returns: `Bool` - True if this proxy uses twoway invocations; false, otherwise.
    func ice_isTwoway() -> Bool

    /// Creates a new proxy that is identical to this proxy, but uses twoway invocations.
    ///
    /// - returns: A new proxy that uses twoway invocations.
    func ice_twoway() -> Self

    /// Returns whether this proxy uses oneway invocations.
    ///
    /// - returns: `Bool` - True if this proxy uses oneway invocations; false, otherwise.
    func ice_isOneway() -> Bool

    /// Creates a new proxy that is identical to this proxy, but uses oneway invocations.
    ///
    /// - returns: A new proxy that uses oneway invocations.
    func ice_oneway() -> Self

    /// Returns whether this proxy uses batch oneway invocations.
    ///
    /// - returns: `Bool` - True if this proxy uses batch oneway invocations; false, otherwise.
    func ice_isBatchOneway() -> Bool

    /// Creates a new proxy that is identical to this proxy, but uses batch oneway invocations.
    ///
    /// - returns: A new proxy that uses batch oneway invocations.
    func ice_batchOneway() -> Self

    /// Returns whether this proxy uses datagram invocations.
    ///
    /// - returns: `Bool` - True if this proxy uses datagram invocations; false, otherwise.
    func ice_isDatagram() -> Bool

    /// Creates a new proxy that is identical to this proxy, but uses datagram invocations.
    ///
    /// - returns: A new proxy that uses datagram invocations.
    func ice_datagram() -> Self

    /// Returns whether this proxy uses batch datagram invocations.
    ///
    /// - returns: `Bool` - True if this proxy uses batch datagram invocations; false, otherwise.
    func ice_isBatchDatagram() -> Bool

    /// Creates a new proxy that is identical to this proxy, but uses batch datagram invocations.
    ///
    /// - returns: A new proxy that uses batch datagram invocations.
    func ice_batchDatagram() -> Self

    /// Obtains the compression override setting of this proxy.
    ///
    /// - returns: `Bool` - The compression override setting. If no optional value is present, no override is
    ///   set. Otherwise, true if compression is enabled, false otherwise.
    func ice_getCompress() -> Bool?

    /// Creates a new proxy that is identical to this proxy, except for compression.
    ///
    /// - parameter _: `Bool` - True enables compression for the new proxy; false disables compression.
    ///
    /// - returns: A new proxy with the specified compression setting.
    func ice_compress(_ compress: Bool) -> Self

    /// Obtains the timeout override of this proxy.
    ///
    /// - returns: `Int32?` - The timeout override. If no optional value is present, no override is set.
    ///   Otherwise, returns the timeout override value.
    func ice_getTimeout() -> Int32?

    /// Creates a new proxy that is identical to this proxy, except for its timeout setting.
    ///
    /// - parameter _: `Int32` - The timeout for the new proxy in milliseconds.
    ///
    /// - returns: A new proxy with the specified timeout.
    func ice_timeout(_ timeout: Int32) -> Self

    /// Returns a proxy that is identical to this proxy, except it's a fixed proxy bound
    /// to the given connection.
    ///
    /// - parameter _: `Ice.Connection` - The fixed proxy connection.
    ///
    /// - returns: A fixed proxy bound to the given connection.
    func ice_fixed(_ connection: Connection) -> Self

    /// Returns whether this proxy is a fixed proxy.
    ///
    /// - returns: `Bool` - True if this is a fixed proxy, false otherwise.
    func ice_isFixed() -> Bool

    /// Returns the cached Connection for this proxy. If the proxy does not yet have an established
    /// connection, it does not attempt to create a connection.
    ///
    /// - returns: `Ice.Connection?` - The cached Connection for this proxy (nil if the proxy does not have
    ///   an established connection).
    ///
    /// - throws: `CollocationOptimizationException` - If the proxy uses collocation optimization and denotes a
    ///   collocated object.
    func ice_getCachedConnection() -> Connection?

    /// Returns the stringified form of this proxy.
    ///
    /// - returns: `String` - The stringified proxy
    func ice_toString() -> String

    /// Returns whether this proxy uses collocation optimization.
    ///
    /// - returns: `Bool` - True if the proxy uses collocation optimization; false, otherwise.
    func ice_isCollocationOptimized() -> Bool

    /// Creates a new proxy that is identical to this proxy, except for collocation optimization.
    ///
    /// - parameter _: `Bool` - True if the new proxy enables collocation optimization; false, otherwise.
    ///
    /// - returns: The new proxy the specified collocation optimization.
    func ice_collocationOptimized(_ collocated: Bool) -> Self
}

/// Casts a proxy to `Ice.ObjectPrx`. This call contacts the server and will throw an Ice run-time exception
/// if the target object does not exist or the server cannot be reached.
///
/// - parameter prx: `Ice.ObjectPrx` - The proxy to cast to `Ice.ObjectPrx`.
///
/// - parameter type: `Ice.ObjectPrx.Protocol` - The proxy type to cast to.
///
/// - parameter facet: `String?` - The optional facet for the new proxy.
///
/// - parameter context: `Ice.Context?` - The optional context dictionary for the invocation.
///
/// - throws: Throws an Ice run-time exception if the target object does not exist, the specified facet
///   does not exist, or the server cannot be reached.
///
/// - returns: The new proxy with the specified facet or nil if the target object does not support the specified
///   interface.
public func checkedCast(prx: Ice.ObjectPrx,
                        type _: ObjectPrx.Protocol,
                        facet: String? = nil,
                        context: Ice.Context? = nil) throws -> ObjectPrx? {
    return try ObjectPrxI.checkedCast(prx: prx, facet: facet, context: context) as ObjectPrxI?
}

/// Creates a new proxy that is identical to the passed proxy, except for its facet. This call does
/// not contact the server and always succeeds.
///
/// - parameter prx: `Ice.ObjectPrx` - The proxy to cast to `Ice.ObjectPrx`.
///
/// - parameter type: `Ice.ObjectPrx.Protocol` - The proxy type to cast to.
///
/// - parameter facet: `String?` - The optional facet for the new proxy.
///
/// - returns: The new proxy with the specified facet.
public func uncheckedCast(prx: Ice.ObjectPrx,
                          type _: ObjectPrx.Protocol,
                          facet: String? = nil) -> ObjectPrx {
    return ObjectPrxI.uncheckedCast(prx: prx, facet: facet) as ObjectPrxI
}

/// Returns the Slice type id of the interface or class associated with this proxy class.
///
/// - returns: `String` - The type id, "::Ice::Object".
public func ice_staticId(_: ObjectPrx.Protocol) -> Swift.String {
    return ObjectTraits.staticId
}

public func != (lhs: ObjectPrx?, rhs: ObjectPrx?) -> Bool {
    return !(lhs == rhs)
}

public func == (lhs: ObjectPrx?, rhs: ObjectPrx?) -> Bool {
    if lhs === rhs {
        return true
    } else if lhs === nil && rhs === nil {
        return true
    } else if lhs === nil || rhs === nil {
        return false
    } else {
        let lhsI = lhs as! ObjectPrxI
        let rhsI = rhs as! ObjectPrxI
        return lhsI.handle.isEqual(rhsI.handle)
    }
}

public extension ObjectPrx {
    /// Returns the underdlying implementation object (Ice internal).
    var _impl: ObjectPrxI {
        return self as! ObjectPrxI
    }

    /// Sends ping request to the target object.
    ///
    /// - parameter context: `Ice.Context` - The optional context dictionary for the invocation.
    ///
    /// - throws: `Ice.LocalException` such as `Ice.ObjectNotExistException` and
    ///   `Ice.ConnectionRefusedException`.
    func ice_ping(context: Context? = nil) throws {
        try _impl._invoke(operation: "ice_ping",
                          mode: OperationMode.Nonmutating,
                          context: context)
    }

    /// Sends ping request to the target object asynchronously.
    ///
    /// - parameter context: `Ice.Context` - The optional context dictionary for the invocation.
    ///
    /// - parameter sentOn: `Dispatch.DispatchQueue` - Optional dispatch queue used to
    ///   dispatch sent callback, the default is to use `PromiseKit.conf.Q.return` queue.
    ///
    /// - parameter sentFlags: `Dispatch.DispatchWorkItemFlags` - Optional dispatch flags used to
    ///   dispatch sent callback
    ///
    /// - parameter sent: `((Swift.Bool) -> Swift.Void)` - Optional sent callback.
    ///
    /// - returns: `PromiseKit.Promise<Void>` - A promise object that will be resolved with
    ///   the return values of invocation.
    func ice_pingAsync(context: Context? = nil,
                       sentOn: DispatchQueue? = PromiseKit.conf.Q.return,
                       sentFlags: DispatchWorkItemFlags? = nil,
                       sent: ((Bool) -> Void)? = nil) -> Promise<Void> {
        return _impl._invokeAsync(operation: "ice_ping",
                                  mode: .Nonmutating,
                                  context: context,
                                  sentOn: sentOn,
                                  sentFlags: sentFlags,
                                  sent: sent)
    }

    /// Tests whether this object supports a specific Slice interface.
    ///
    /// - parameter id: `String` - The type ID of the Slice interface to test against.
    ///
    /// - parameter context: `Ice.Context` - The optional context dictionary for the invocation.
    ///
    /// - returns: `Bool` - True if the target object has the interface specified by id or derives
    ///   from the interface specified by id.
    func ice_isA(id: String, context: Context? = nil) throws -> Bool {
        return try _impl._invoke(operation: "ice_isA",
                                 mode: .Nonmutating,
                                 write: { ostr in
                                     ostr.write(id)
                                 },
                                 read: { istr in try istr.read() as Bool },
                                 context: context)
    }

    /// Tests whether this object supports a specific Slice interface.
    ///
    /// - parameter id: `String` - The type ID of the Slice interface to test against.
    ///
    /// - parameter context: `Ice.Context` - The optional context dictionary for the invocation.
    ///
    /// - parameter sentOn: `Dispatch.DispatchQueue` - Optional dispatch queue used to
    ///   dispatch sent callback, the default is to use `PromiseKit.conf.Q.return` queue.
    ///
    /// - parameter sentFlags: `Dispatch.DispatchWorkItemFlags` - Optional dispatch flags used to
    ///   dispatch sent callback
    ///
    /// - parameter sent: `((Bool) -> Void)` - Optional sent callback.
    ///
    /// - returns: `PromiseKit.Promise<Bool>` - A promise object that will be resolved with
    ///   the return values of invocation.
    func ice_isAAsync(id: String, context: Context? = nil,
                      sentOn: DispatchQueue? = PromiseKit.conf.Q.return,
                      sentFlags: DispatchWorkItemFlags? = nil,
                      sent: ((Bool) -> Void)? = nil) -> Promise<Bool> {
        return _impl._invokeAsync(operation: "ice_isA",
                                  mode: .Nonmutating,
                                  write: { ostr in
                                      ostr.write(id)
                                  },
                                  read: { istr in try istr.read() as Bool },
                                  context: context,
                                  sentOn: sentOn,
                                  sentFlags: sentFlags,
                                  sent: sent)
    }

    /// Returns the Slice type ID of the most-derived interface supported by the target object of this proxy.
    ///
    /// - parameter context: `Ice.Context?` - The optional context dictionary for the invocation.
    ///
    /// - returns: `String` - The Slice type ID of the most-derived interface.
    func ice_id(context: Context? = nil) throws -> String {
        return try _impl._invoke(operation: "ice_id",
                                 mode: .Nonmutating,
                                 read: { istr in try istr.read() as String },
                                 context: context)
    }

    /// Returns the Slice type ID of the most-derived interface supported by the target object of this proxy.
    ///
    /// - parameter context: `Ice.Context?` - The optional context dictionary for the invocation.
    ///
    /// - parameter sentOn: `Dispatch.DispatchQueue` - Optional dispatch queue used to
    ///   dispatch sent callback, the default is to use `PromiseKit.conf.Q.return` queue.
    ///
    /// - parameter sentFlags: `Dispatch.DispatchWorkItemFlags` - Optional dispatch flags used to
    ///   dispatch sent callback
    ///
    /// - parameter sent: `((Bool) -> Void)` - Optional sent callback.
    ///
    /// - returns: `PromiseKit.Promise<String>` A promise object that will be resolved with
    ///   the return values of invocation.
    func ice_idAsync(context: Context? = nil,
                     sentOn: DispatchQueue? = PromiseKit.conf.Q.return,
                     sentFlags: DispatchWorkItemFlags? = nil,
                     sent: ((Bool) -> Void)? = nil) -> Promise<String> {
        return _impl._invokeAsync(operation: "ice_id",
                                  mode: .Nonmutating,
                                  read: { istr in try istr.read() as String },
                                  context: context,
                                  sentOn: sentOn,
                                  sentFlags: sentFlags,
                                  sent: sent)
    }

    /// Returns the Slice type IDs of the interfaces supported by the target object of this proxy.
    ///
    /// - parameter context: `Ice.Context?` - The optional context dictionary for the invocation.
    ///
    /// - returns: `Ice.StringSeq` - The Slice type IDs of the interfaces supported by the target object,
    ///   in base-to-derived order. The first element of the returned array is always `::Ice::Object`.
    func ice_ids(context: Context? = nil) throws -> StringSeq {
        return try _impl._invoke(operation: "ice_ids",
                                 mode: .Nonmutating,
                                 read: { istr in try istr.read() as StringSeq },
                                 context: context)
    }

    /// Returns the Slice type IDs of the interfaces supported by the target object of this proxy.
    ///
    /// - parameter context: `Ice.Context?` - The optional context dictionary for the invocation.
    ///
    /// - parameter sentOn: `Dispatch.DispatchQueue` - Optional dispatch queue used to
    ///   dispatch sent callback, the default is to use `PromiseKit.conf.Q.return` queue.
    ///
    /// - parameter sentFlags: `Dispatch.DispatchWorkItemFlags` - Optional dispatch flags used to
    ///   dispatch sent callback
    ///
    /// - parameter sent: `((Bool) -> Void)` - Optional sent callback.
    ///
    /// - returns: `PromiseKit.Promise<Ice.StringSeq>` - A promise object that will be resolved with
    ///   the return values of invocation.
    func ice_idsAsync(context: Context? = nil,
                      sentOn: DispatchQueue? = PromiseKit.conf.Q.return,
                      sentFlags: DispatchWorkItemFlags? = nil,
                      sent: ((Bool) -> Void)? = nil) -> Promise<StringSeq> {
        return _impl._invokeAsync(operation: "ice_ids",
                                  mode: .Nonmutating,
                                  read: { istr in try istr.read() as StringSeq },
                                  context: context,
                                  sentOn: sentOn,
                                  sentFlags: sentFlags,
                                  sent: sent)
    }

    /// Invokes an operation dynamically.
    ///
    /// - parameter operation: `String` - The name of the operation to invoke.
    ///
    /// - parameter mode: `Ice.OperationMode` - The operation mode (normal or idempotent).
    ///
    /// - parameter inEncaps: `Data` - The encoded in-parameters for the operation.
    ///
    /// - parameter context: `Ice.Context` - The context dictionary for the invocation.
    ///
    /// - returns: A tuple with the following fields:
    ///
    ///   - ok: `Bool` - If the operation completed successfully, the value
    ///     is set to true. If the operation raises a user exception, the return value
    ///     is false; in this case, outEncaps contains the encoded user exception. If
    ///     the operation raises a run-time exception, it throws it directly.
    ///
    ///   - outEncaps: `Data` - The encoded out-paramaters and return value for the operation.
    ///     The return value follows any out-parameters.
    func ice_invoke(operation: String,
                    mode: OperationMode,
                    inEncaps: Data,
                    context: Context? = nil) throws -> (ok: Bool, outEncaps: Data) {
        if _impl.isTwoway {
            var data: Data?
            var ok: Bool = false
            try _impl.handle.invoke(operation, mode: mode.rawValue, inParams: inEncaps, context: context) {
                ok = $0
                data = Data($1) // make a copy
            }
            return (ok, data!)
        } else {
            try _impl.handle.onewayInvoke(operation, mode: mode.rawValue, inParams: inEncaps, context: context)
            return (true, Data())
        }
    }

    /// Invokes an operation dynamically.
    ///
    /// - parameter operation: `String` - The name of the operation to invoke.
    ///
    /// - parameter mode: `Ice.OperationMode` - The operation mode (normal or idempotent).
    ///
    /// - parameter inEncaps: `Data` - The encoded in-parameters for the operation.
    ///
    /// - parameter context: `Ice.Context` - The context dictionary for the invocation.
    ///
    /// - parameter sentOn: `Dispatch.DispatchQueue` - Optional dispatch queue used to
    ///   dispatch sent callback, the default is to use `PromiseKit.conf.Q.return` queue.
    ///
    /// - parameter sentFlags: `Dispatch.DispatchWorkItemFlags` - Optional dispatch flags used to
    ///   dispatch sent callback.
    ///
    /// - parameter sent: `((Bool) -> Void)` - Optional sent callback.
    ///
    /// - returns: `PromiseKit.Promise<(ok: Bool, outEncaps: Data)>` - A promise object that will be
    ////  resolved with the return values of the invocation.
    func ice_invokeAsync(operation: String,
                         mode: OperationMode,
                         inEncaps: Data,
                         context: Context? = nil,
                         sentOn: DispatchQueue? = nil,
                         sentFlags: DispatchWorkItemFlags? = nil,
                         sent: ((Bool) -> Void)? = nil) -> Promise<(ok: Bool, outEncaps: Data)> {
        if _impl.isTwoway {
            return Promise<(ok: Bool, outEncaps: Data)> { seal in
                _impl.handle.invokeAsync(operation,
                                         mode: mode.rawValue,
                                         inParams: inEncaps,
                                         context: context,
                                         response: { ok, encaps in
                                             do {
                                                 let istr =
                                                     InputStream(communicator: self._impl.communicator,
                                                                 encoding: self._impl.encoding,
                                                                 bytes: Data(encaps)) // make a copy
                                                 seal.fulfill((ok, try istr.readEncapsulation().bytes))
                                             } catch {
                                                 seal.reject(error)
                                             }
                                         },
                                         exception: { error in
                                             seal.reject(error)
                                         },
                                         sent: createSentCallback(sentOn: sentOn,
                                                                  sentFlags: sentFlags,
                                                                  sent: sent))
            }
        } else {
            let sentCB = createSentCallback(sentOn: sentOn, sentFlags: sentFlags, sent: sent)
            return Promise<(ok: Bool, outEncaps: Data)> { seal in
                _impl.handle.invokeAsync(operation,
                                         mode: mode.rawValue,
                                         inParams: inEncaps,
                                         context: context,
                                         response: { _, _ in
                                             fatalError("Unexpected response")
                                         },
                                         exception: { error in
                                             seal.reject(error)
                                         },
                                         sent: {
                                             seal.fulfill((true, Data()))
                                             if let sentCB = sentCB {
                                                 sentCB($0)
                                             }
                })
            }
        }
    }

    /// Returns the connection for this proxy. If the proxy does not yet have an established connection,
    /// it first attempts to create a connection.
    ///
    /// - returns: `Ice.Connection?` - The Connection for this proxy.
    ///
    /// - throws: `Ice.CollocationOptimizationException` - If the proxy uses collocation optimization and denotes a
    ///   collocated object.
    func ice_getConnection() throws -> Connection? {
        return try autoreleasepool {
            //
            // Returns Any which is either NSNull or ICEConnection
            //
            guard let handle = try _impl.handle.ice_getConnection() as? ICEConnection else {
                return nil
            }
            return handle.getSwiftObject(ConnectionI.self) { ConnectionI(handle: handle) }
        }
    }

    /// Returns the connection for this proxy. If the proxy does not yet have an established connection,
    /// it first attempts to create a connection.
    ///
    /// - returns: `PromiseKit.Promise<Ice.Connection?>` - A promise object that will be resolved with
    ///   the return values of invocation.
    ///
    /// - throws: `Ice.CollocationOptimizationException` - If the proxy uses collocation optimization and denotes a
    ///   collocated object.
    func ice_getConnectionAsync() -> Promise<Connection?> {
        return Promise<Connection?> { seal in
            self._impl.handle.ice_getConnectionAsync({ conn in
                seal.fulfill(conn?.getSwiftObject(ConnectionI.self) {
                    ConnectionI(handle: conn!)
                })
            }, exception: { ex in seal.reject(ex) })
        }
    }

    /// Flushes any pending batched requests for this communicator. The call blocks until the flush is complete.
    func ice_flushBatchRequests() throws {
        return try autoreleasepool {
            try _impl.handle.ice_flushBatchRequests()
        }
    }

    /// Asynchronously flushes any pending batched requests for this proxy.
    ///
    /// - parameter sentOn: `Dispatch.DispatchQueue` - Optional dispatch queue used to
    ///   dispatch sent callback, the default is to use `PromiseKit.conf.Q.return` queue.
    ///
    /// - parameter sentFlags: `Dispatch.DispatchWorkItemFlags` Optional dispatch flags used to
    ///   dispatch sent callback.
    ///
    /// - parameter sent: `((Bool) -> Void)` - Optional sent callback.
    ///
    /// - returns: `PromiseKit.Promise<Void> - A promise object that will be resolved when
    ///   the flush is complete.
    func ice_flushBatchRequestsAsync(sentOn: DispatchQueue? = PromiseKit.conf.Q.return,
                                     sentFlags: DispatchWorkItemFlags? = nil.self,
                                     sent: ((Bool) -> Void)? = nil) -> Promise<Void> {
        let sentCB = createSentCallback(sentOn: sentOn, sentFlags: sentFlags, sent: sent)
        return Promise<Void> { seal in
            _impl.handle.ice_flushBatchRequestsAsync(
                exception: {
                    seal.reject($0)
                },
                sent: {
                    seal.fulfill(())
                    if let sentCB = sentCB {
                        sentCB($0)
                    }
                }
            )
        }
    }
}

//
// ObjectPrxI, the base proxy implementation class is an Ice-internal class used in the
// generated code - this is why we give it the open access level.
//
open class ObjectPrxI: ObjectPrx {
    internal let handle: ICEObjectPrx
    internal let communicator: Communicator
    internal let encoding: EncodingVersion
    fileprivate let isTwoway: Bool

    public var description: String {
        return handle.ice_toString()
    }

    public required init(handle: ICEObjectPrx, communicator: Communicator) {
        self.handle = handle
        self.communicator = communicator
        var encoding = EncodingVersion()
        handle.ice_getEncodingVersion(&encoding.major, minor: &encoding.minor)
        self.encoding = encoding
        isTwoway = handle.ice_isTwoway()
    }

    public required init(from prx: ObjectPrx) {
        let impl = prx as! ObjectPrxI
        handle = impl.handle
        communicator = impl.communicator
        encoding = impl.encoding
        isTwoway = impl.isTwoway
    }

    internal func fromICEObjectPrx<ObjectPrxType>(_ h: ICEObjectPrx) -> ObjectPrxType where ObjectPrxType: ObjectPrxI {
        return ObjectPrxType(handle: h, communicator: communicator)
    }

    internal static func fromICEObjectPrx(handle: ICEObjectPrx,
                                          communicator c: Communicator? = nil) -> Self {
        let communicator = c ?? handle.ice_getCommunicator().getCachedSwiftObject(CommunicatorI.self)
        return self.init(handle: handle, communicator: communicator)
    }

    public func ice_getCommunicator() -> Communicator {
        return communicator
    }

    open class func ice_staticId() -> String {
        return ObjectTraits.staticId
    }

    public func ice_getIdentity() -> Identity {
        var name = NSString()
        var category = NSString()
        handle.ice_getIdentity(&name, category: &category)
        return Identity(name: name as String, category: category as String)
    }

    public func ice_identity(_ id: Identity) -> Self {
        precondition(!id.name.isEmpty, "Identity name cannot be empty")
        do {
            return try autoreleasepool {
                try fromICEObjectPrx(handle.ice_identity(id.name, category: id.category))
            }
        } catch {
            fatalError("\(error)")
        }
    }

    public func ice_getContext() -> Context {
        return handle.ice_getContext() as Context
    }

    public func ice_context(_ context: Context) -> Self {
        return fromICEObjectPrx(handle.ice_context(context))
    }

    public func ice_getFacet() -> String {
        return handle.ice_getFacet()
    }

    public func ice_facet(_ facet: String) -> ObjectPrx {
        return fromICEObjectPrx(handle.ice_facet(facet))
    }

    public func ice_getAdapterId() -> String {
        return handle.ice_getAdapterId()
    }

    public func ice_adapterId(_ id: String) -> Self {
        precondition(!ice_isFixed(), "Cannot create a fixed proxy with an adapterId")
        do {
            return try autoreleasepool {
                try fromICEObjectPrx(handle.ice_adapterId(id))
            }
        } catch {
            fatalError("\(error)")
        }
    }

    public func ice_getEndpoints() -> EndpointSeq {
        return handle.ice_getEndpoints().fromObjc()
    }

    public func ice_endpoints(_ endpoints: EndpointSeq) -> Self {
        precondition(!ice_isFixed(), "Cannot create a fixed proxy with endpoints")
        do {
            return try autoreleasepool {
                try fromICEObjectPrx(handle.ice_endpoints(endpoints.toObjc()))
            }
        } catch {
            fatalError("\(error)")
        }
    }

    public func ice_getLocatorCacheTimeout() -> Int32 {
        return handle.ice_getLocatorCacheTimeout()
    }

    public func ice_locatorCacheTimeout(_ timeout: Int32) -> Self {
        precondition(!ice_isFixed(), "Cannot create a fixed proxy with a locatorCacheTimeout")
        precondition(timeout >= -1, "Invalid locator cache timeout value")
        do {
            return try autoreleasepool {
                try fromICEObjectPrx(handle.ice_locatorCacheTimeout(timeout))
            }
        } catch {
            fatalError("\(error)")
        }
    }

    public func ice_getInvocationTimeout() -> Int32 {
        return handle.ice_getInvocationTimeout()
    }

    public func ice_invocationTimeout(_ timeout: Int32) -> Self {
        precondition(timeout >= 1 || timeout == -1 || timeout == -2, "Invalid invocation timeout value")
        do {
            return try autoreleasepool {
                try fromICEObjectPrx(handle.ice_invocationTimeout(timeout))
            }
        } catch {
            fatalError("\(error)")
        }
    }

    public func ice_getConnectionId() -> String {
        return handle.ice_getConnectionId()
    }

    public func ice_connectionId(_ id: String) -> Self {
        precondition(!ice_isFixed(), "Cannot create a fixed proxy with a connectionId")
        do {
            return try autoreleasepool {
                try fromICEObjectPrx(handle.ice_connectionId(id))
            }
        } catch {
            fatalError("\(error)")
        }
    }

    public func ice_isConnectionCached() -> Bool {
        return handle.ice_isConnectionCached()
    }

    public func ice_connectionCached(_ cached: Bool) -> Self {
        precondition(!ice_isFixed(), "Cannot create a fixed proxy with a cached connection")
        do {
            return try autoreleasepool {
                try fromICEObjectPrx(handle.ice_connectionCached(cached))
            }
        } catch {
            fatalError("\(error)")
        }
    }

    public func ice_getEndpointSelection() -> EndpointSelectionType {
        return EndpointSelectionType(rawValue: handle.ice_getEndpointSelection())!
    }

    public func ice_endpointSelection(_ type: EndpointSelectionType) -> Self {
        precondition(!ice_isFixed(), "Cannot create a fixed proxy with an endpointSelectionType")
        do {
            return try autoreleasepool {
                try fromICEObjectPrx(handle.ice_endpointSelection(type.rawValue))
            }
        } catch {
            fatalError("\(error)")
        }
    }

    public func ice_getEncodingVersion() -> EncodingVersion {
        return encoding
    }

    public func ice_encodingVersion(_ encoding: EncodingVersion) -> Self {
        return fromICEObjectPrx(handle.ice_encodingVersion(encoding.major, minor: encoding.minor))
    }

    public func ice_getRouter() -> RouterPrx? {
        guard let routerHandle = handle.ice_getRouter() else {
            return nil
        }
        return fromICEObjectPrx(routerHandle) as RouterPrxI
    }

    public func ice_router(_ router: RouterPrx?) -> Self {
        precondition(!ice_isFixed(), "Cannot create a fixed proxy with a router")
        do {
            return try autoreleasepool {
                let r = router as? ObjectPrxI
                return try fromICEObjectPrx(handle.ice_router(r?.handle ?? nil))
            }
        } catch {
            fatalError("\(error)")
        }
    }

    public func ice_getLocator() -> LocatorPrx? {
        guard let locatorHandle = handle.ice_getLocator() else {
            return nil
        }
        return fromICEObjectPrx(locatorHandle) as LocatorPrxI
    }

    public func ice_locator(_ locator: LocatorPrx?) -> Self {
        precondition(!ice_isFixed(), "Cannot create a fixed proxy with a locator")
        do {
            return try autoreleasepool {
                let l = locator as? ObjectPrxI
                return try fromICEObjectPrx(handle.ice_locator(l?.handle ?? nil))
            }
        } catch {
            fatalError("\(error)")
        }
    }

    public func ice_isSecure() -> Bool {
        return handle.ice_isSecure()
    }

    public func ice_secure(_ secure: Bool) -> Self {
        return fromICEObjectPrx(handle.ice_secure(secure))
    }

    public func ice_isPreferSecure() -> Bool {
        return handle.ice_isPreferSecure()
    }

    public func ice_preferSecure(_ preferSecure: Bool) -> Self {
        precondition(!ice_isFixed(), "Cannot create a fixed proxy with preferSecure")
        do {
            return try autoreleasepool {
                try fromICEObjectPrx(handle.ice_preferSecure(preferSecure))
            }
        } catch {
            fatalError("\(error)")
        }
    }

    public func ice_isTwoway() -> Bool {
        return isTwoway
    }

    public func ice_twoway() -> Self {
        return fromICEObjectPrx(handle.ice_twoway())
    }

    public func ice_isOneway() -> Bool {
        return handle.ice_isOneway()
    }

    public func ice_oneway() -> Self {
        return fromICEObjectPrx(handle.ice_oneway())
    }

    public func ice_isBatchOneway() -> Bool {
        return handle.ice_isBatchOneway()
    }

    public func ice_batchOneway() -> Self {
        return fromICEObjectPrx(handle.ice_batchOneway())
    }

    public func ice_isDatagram() -> Bool {
        return handle.ice_isDatagram()
    }

    public func ice_datagram() -> Self {
        return fromICEObjectPrx(handle.ice_datagram())
    }

    public func ice_isBatchDatagram() -> Bool {
        return handle.ice_isBatchDatagram()
    }

    public func ice_batchDatagram() -> Self {
        return fromICEObjectPrx(handle.ice_batchDatagram())
    }

    public func ice_getCompress() -> Bool? {
        guard let compress = handle.ice_getCompress() as? Bool? else {
            preconditionFailure("Bool? type was expected")
        }
        return compress
    }

    public func ice_compress(_ compress: Bool) -> Self {
        return fromICEObjectPrx(handle.ice_compress(compress))
    }

    public func ice_getTimeout() -> Int32? {
        guard let timeout = handle.ice_getTimeout() as? Int32? else {
            preconditionFailure("Int32? type was expected")
        }
        return timeout
    }

    public func ice_timeout(_ timeout: Int32) -> Self {
        precondition(!ice_isFixed(), "Cannot create a fixed proxy with a connection timeout")
        precondition(timeout > 0 || timeout == -1, "Invalid connection timeout value")
        do {
            return try autoreleasepool {
                try fromICEObjectPrx(handle.ice_timeout(timeout))
            }
        } catch {
            fatalError("\(error)")
        }
    }

    public func ice_fixed(_ connection: Connection) -> Self {
        do {
            return try autoreleasepool {
                try fromICEObjectPrx(handle.ice_fixed((connection as! ConnectionI).handle))
            }
        } catch {
            fatalError("\(error)")
        }
    }

    public func ice_isFixed() -> Bool {
        return handle.ice_isFixed()
    }

    public func ice_getCachedConnection() -> Connection? {
        guard let handle = handle.ice_getCachedConnection() else {
            return nil
        }
        return handle.getSwiftObject(ConnectionI.self) { ConnectionI(handle: handle) }
    }

    public func ice_write(to os: OutputStream) {
        handle.ice_write(os, encodingMajor: os.currentEncoding.major, encodingMinor: os.currentEncoding.minor)
    }

    public func ice_toString() -> String {
        return handle.ice_toString()
    }

    public func ice_isCollocationOptimized() -> Bool {
        return handle.ice_isCollocationOptimized()
    }

    public func ice_collocationOptimized(_ collocated: Bool) -> Self {
        precondition(!ice_isFixed(), "Cannot create a fixed proxy with collocation optimization")
        do {
            return try autoreleasepool {
                try fromICEObjectPrx(handle.ice_collocationOptimized(collocated))
            }
        } catch {
            fatalError("\(error)")
        }
    }

    public static func ice_read(from istr: InputStream) throws -> Self? {
        //
        // Unmarshaling of proxies is done in C++. Since we don't know how big this proxy will
        // be we pass the current buffer position and remaining buffer capacity.
        //

        // The number of bytes consumed reading the proxy
        var bytesRead: Int = 0
        let encoding = istr.currentEncoding
        let communicator = istr.communicator

        //
        // Returns Any which is either NSNull or ICEObjectPrx
        //
        let handleOpt = try ICEObjectPrx.ice_read(istr.data[istr.pos ..< istr.data.count],
                                                  communicator: (communicator as! CommunicatorI).handle,
                                                  encodingMajor: encoding.major,
                                                  encodingMinor: encoding.minor,
                                                  bytesRead: &bytesRead) as? ICEObjectPrx

        // Since the proxy was read in C++ we need to skip over the bytes which were read
        // We avoid using a defer statment for this since you can not throw from one
        try istr.skip(bytesRead)

        guard let handle = handleOpt else {
            return nil
        }

        return self.init(handle: handle, communicator: communicator)
    }

    public func _invoke(operation: String,
                        mode: OperationMode,
                        format: FormatType = FormatType.DefaultFormat,
                        write: ((OutputStream) -> Void)? = nil,
                        userException: ((UserException) throws -> Void)? = nil,
                        context: Context? = nil) throws {
        if userException != nil, !isTwoway {
            throw TwowayOnlyException(operation: operation)
        }

        let ostr = OutputStream(communicator: communicator)
        if let write = write {
            ostr.startEncapsulation(encoding: encoding, format: format)
            write(ostr)
            ostr.endEncapsulation()
        }

        if isTwoway {
            var uex: Error?
            try autoreleasepool {
                try handle.invoke(operation, mode: mode.rawValue,
                                  inParams: ostr.finished(), context: context,
                                  response: { ok, encaps in
                                      do {
                                          let istr = InputStream(communicator: self.communicator,
                                                                 encoding: self.encoding,
                                                                 bytes: encaps)
                                          if ok == false {
                                              try ObjectPrxI.throwUserException(istr: istr,
                                                                                userException: userException)
                                          }
                                          try istr.skipEmptyEncapsulation()
                                      } catch {
                                          uex = error
                                      }
                })

                if let e = uex {
                    throw e
                }
            }
        } else {
            try autoreleasepool {
                try handle.onewayInvoke(operation,
                                        mode: mode.rawValue,
                                        inParams: ostr.finished(),
                                        context: context)
            }
        }
    }

    public func _invoke<T>(operation: String,
                           mode: OperationMode,
                           format: FormatType = FormatType.DefaultFormat,
                           write: ((OutputStream) -> Void)? = nil,
                           read: @escaping (InputStream) throws -> T,
                           userException: ((UserException) throws -> Void)? = nil,
                           context: Context? = nil) throws -> T {
        if !isTwoway {
            throw TwowayOnlyException(operation: operation)
        }
        let ostr = OutputStream(communicator: communicator)
        if let write = write {
            ostr.startEncapsulation(encoding: encoding, format: format)
            write(ostr)
            ostr.endEncapsulation()
        }
        var uex: Error?
        var ret: T!
        try autoreleasepool {
            try handle.invoke(operation,
                              mode: mode.rawValue,
                              inParams: ostr.finished(),
                              context: context,
                              response: { ok, encaps in
                                  do {
                                      let istr = InputStream(communicator: self.communicator,
                                                             encoding: self.encoding,
                                                             bytes: encaps)
                                      if ok == false {
                                          try ObjectPrxI.throwUserException(istr: istr,
                                                                            userException: userException)
                                      }
                                      try istr.startEncapsulation()
                                      ret = try read(istr)
                                      try istr.endEncapsulation()
                                  } catch {
                                      uex = error
                                  }
            })

            if let e = uex {
                throw e
            }
        }

        precondition(ret != nil)
        return ret
    }

    public func _invokeAsync(operation: String,
                             mode: OperationMode,
                             format: FormatType = FormatType.DefaultFormat,
                             write: ((OutputStream) -> Void)? = nil,
                             userException: ((UserException) throws -> Void)? = nil,
                             context: Context? = nil,
                             sentOn: DispatchQueue? = PromiseKit.conf.Q.return,
                             sentFlags: DispatchWorkItemFlags? = nil,
                             sent: ((Bool) -> Void)? = nil) -> Promise<Void> {
        if userException != nil, !isTwoway {
            return Promise(error: TwowayOnlyException(operation: operation))
        }
        let ostr = OutputStream(communicator: communicator)
        if let write = write {
            ostr.startEncapsulation(encoding: encoding, format: format)
            write(ostr)
            ostr.endEncapsulation()
        }
        if isTwoway {
            return Promise<Void> { seal in
                handle.invokeAsync(operation,
                                   mode: mode.rawValue,
                                   inParams: ostr.finished(),
                                   context: context,
                                   response: { ok, encaps in
                                       do {
                                           let istr = InputStream(communicator: self.communicator,
                                                                  encoding: self.encoding,
                                                                  bytes: encaps)
                                           if ok == false {
                                               try ObjectPrxI.throwUserException(istr: istr,
                                                                                 userException: userException)
                                           }
                                           try istr.skipEmptyEncapsulation()
                                           seal.fulfill(())
                                       } catch {
                                           seal.reject(error)
                                       }
                                   },
                                   exception: { error in
                                       seal.reject(error)
                                   },
                                   sent: createSentCallback(sentOn: sentOn, sentFlags: sentFlags, sent: sent))
            }
        } else {
            if ice_isBatchOneway() || ice_isBatchDatagram() {
                return Promise<Void> { seal in
                    try autoreleasepool {
                        try handle.onewayInvoke(operation,
                                                mode: mode.rawValue,
                                                inParams: ostr.finished(),
                                                context: context)

                        seal.fulfill(())
                    }
                }
            } else {
                return Promise<Void> { seal in
                    let sentCB = createSentCallback(sentOn: sentOn, sentFlags: sentFlags, sent: sent)
                    handle.invokeAsync(operation,
                                       mode: mode.rawValue,
                                       inParams: ostr.finished(),
                                       context: context,
                                       response: { _, _ in
                                           fatalError("Unexpected response")
                                       },
                                       exception: { error in
                                           seal.reject(error)
                                       },
                                       sent: {
                                           seal.fulfill(())
                                           if let sentCB = sentCB {
                                               sentCB($0)
                                           }
                    })
                }
            }
        }
    }

    public func _invokeAsync<T>(operation: String,
                                mode: OperationMode,
                                format: FormatType = FormatType.DefaultFormat,
                                write: ((OutputStream) -> Void)? = nil,
                                read: @escaping (InputStream) throws -> T,
                                userException: ((UserException) throws -> Void)? = nil,
                                context: Context? = nil,
                                sentOn: DispatchQueue? = PromiseKit.conf.Q.return,
                                sentFlags: DispatchWorkItemFlags? = nil,
                                sent: ((Bool) -> Void)? = nil) -> Promise<T> {
        if !isTwoway {
            return Promise(error: TwowayOnlyException(operation: operation))
        }
        let ostr = OutputStream(communicator: communicator)
        if let write = write {
            ostr.startEncapsulation(encoding: encoding, format: format)
            write(ostr)
            ostr.endEncapsulation()
        }
        return Promise<T> { seal in
            handle.invokeAsync(operation,
                               mode: mode.rawValue,
                               inParams: ostr.finished(),
                               context: context,
                               response: { ok, encaps in
                                   do {
                                       let istr = InputStream(communicator: self.communicator,
                                                              encoding: self.encoding,
                                                              bytes: encaps)
                                       if ok == false {
                                           try ObjectPrxI.throwUserException(istr: istr,
                                                                             userException: userException)
                                       }
                                       try istr.startEncapsulation()
                                       let l = try read(istr)
                                       try istr.endEncapsulation()
                                       seal.fulfill(l)
                                   } catch {
                                       seal.reject(error)
                                   }
                               },
                               exception: { error in
                                   seal.reject(error)
                               },
                               sent: createSentCallback(sentOn: sentOn, sentFlags: sentFlags, sent: sent))
        }
    }

    private static func throwUserException(istr: InputStream, userException: ((UserException) throws -> Void)?) throws {
        do {
            try istr.startEncapsulation()
            try istr.throwException()
        } catch let error as UserException {
            try istr.endEncapsulation()
            if let userException = userException {
                try userException(error)
            }
            throw UnknownUserException(unknown: error.ice_id())
        }
        fatalError("Failed to throw user exception")
    }

    public static func checkedCast<ProxyImpl>(prx: ObjectPrx,
                                              facet: String? = nil,
                                              context: Context? = nil) throws -> ProxyImpl?
        where ProxyImpl: ObjectPrxI {
        do {
            let objPrx = facet != nil ? prx.ice_facet(facet!) : prx

            // checkedCast always calls ice_isA - no optimization on purpose
            guard try objPrx.ice_isA(id: ProxyImpl.ice_staticId(), context: context) else {
                return nil
            }
            return ProxyImpl(from: objPrx)
        } catch is FacetNotExistException {
            return nil
        }
    }

    public static func uncheckedCast<ProxyImpl>(prx: ObjectPrx,
                                                facet: String? = nil) -> ProxyImpl where ProxyImpl: ObjectPrxI {
        if let f = facet {
            return ProxyImpl(from: prx.ice_facet(f))
        } else if let optimized = prx as? ProxyImpl {
            return optimized
        } else {
            return ProxyImpl(from: prx)
        }
    }
}