You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@thrift.apache.org by je...@apache.org on 2015/10/09 22:05:58 UTC

[1/7] thrift git commit: THRIFT-2905 Cocoa compiler should have option to produce "modern" Objective-C Client: Cocoa (ObjectiveC & Swift) Author: Kevin Wooten

Repository: thrift
Updated Branches:
  refs/heads/master 983bf7de4 -> 56e5b9b01


http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/TSSLSocketTransportError.m
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/TSSLSocketTransportError.m b/lib/cocoa/src/transport/TSSLSocketTransportError.m
new file mode 100644
index 0000000..bcf941c
--- /dev/null
+++ b/lib/cocoa/src/transport/TSSLSocketTransportError.m
@@ -0,0 +1,23 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#import "TSSLSocketTransportError.h"
+
+
+NSString *TSSLSocketTransportErrorDomain = @"TSSLSocketTransportErrorDomain";

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/TSocketClient.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/TSocketClient.h b/lib/cocoa/src/transport/TSocketClient.h
deleted file mode 100644
index 81a0247..0000000
--- a/lib/cocoa/src/transport/TSocketClient.h
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#import <Foundation/Foundation.h>
-#import "TNSStreamTransport.h"
-
-@interface TSocketClient : TNSStreamTransport 
-#if TARGET_OS_IPHONE || (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6)
-<NSStreamDelegate>
-#endif
-{
-}
-
-- (id) initWithHostname: (NSString *) hostname
-                   port: (UInt32) port;
-
-@end
-
-
-

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/TSocketClient.m
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/TSocketClient.m b/lib/cocoa/src/transport/TSocketClient.m
deleted file mode 100644
index b0bac74..0000000
--- a/lib/cocoa/src/transport/TSocketClient.m
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-#import "TSocketClient.h"
-#import "TObjective-C.h"
-
-#if !TARGET_OS_IPHONE
-#import <CoreServices/CoreServices.h>
-#else
-#import <CFNetwork/CFNetwork.h>
-#endif
-
-@interface TSocketClient ()
-{
-    NSInputStream * inputStream;
-	NSOutputStream * outputStream;
-}
-@end
-
-@implementation TSocketClient
-
-- (id) initWithHostname: (NSString *) hostname
-                   port: (UInt32) port
-{
-	inputStream = NULL;
-	outputStream = NULL;
-	CFReadStreamRef readStream = NULL;
-	CFWriteStreamRef writeStream = NULL;
-	CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (bridge_stub CFStringRef)hostname, port, &readStream, &writeStream);
-	if (readStream && writeStream) {
-		CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
-		CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
-		
-		inputStream = (bridge_stub NSInputStream *)readStream;
-		[inputStream retain_stub];
-		[inputStream setDelegate:self];
-		[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
-		[inputStream open];
-		
-		outputStream = (bridge_stub NSOutputStream *)writeStream;
-		[outputStream retain_stub];
-		[outputStream setDelegate:self];
-		[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
-		[outputStream open];
-        CFRelease(readStream);
-        CFRelease(writeStream);
-	}
-	
-	self = [super initWithInputStream: inputStream outputStream: outputStream];
-	
-	return self;
-}
-
--(void)dealloc
-{
-    [inputStream close];
-    [inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
-    [inputStream setDelegate:nil];
-    [inputStream release_stub];
-    
-    [outputStream close];
-    [outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
-    [outputStream setDelegate:nil];
-    [outputStream release_stub];
-    [super dealloc_stub];
-}
-
-
-@end
-
-
-

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/TSocketTransport.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/TSocketTransport.h b/lib/cocoa/src/transport/TSocketTransport.h
new file mode 100644
index 0000000..4ea03cc
--- /dev/null
+++ b/lib/cocoa/src/transport/TSocketTransport.h
@@ -0,0 +1,34 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#import <Foundation/Foundation.h>
+#import "TNSStreamTransport.h"
+
+NS_ASSUME_NONNULL_BEGIN
+
+
+@interface TSocketTransport : TNSStreamTransport
+
+-(id) initWithHostname:(NSString *)hostname
+                  port:(int)port;
+
+@end
+
+
+NS_ASSUME_NONNULL_END

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/TSocketTransport.m
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/TSocketTransport.m b/lib/cocoa/src/transport/TSocketTransport.m
new file mode 100644
index 0000000..1b8fe9b
--- /dev/null
+++ b/lib/cocoa/src/transport/TSocketTransport.m
@@ -0,0 +1,73 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#import "TSocketTransport.h"
+
+#if !TARGET_OS_IPHONE
+#import <CoreServices/CoreServices.h>
+#else
+#import <CFNetwork/CFNetwork.h>
+#endif
+
+@interface TSocketTransport () <NSStreamDelegate>
+@end
+
+
+@implementation TSocketTransport
+
+-(id) initWithHostname:(NSString *)hostname
+                  port:(int)port
+{
+  NSInputStream *inputStream = nil;
+  NSOutputStream *outputStream = nil;
+
+  CFReadStreamRef readStream = NULL;
+  CFWriteStreamRef writeStream = NULL;
+  CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (__bridge CFStringRef)hostname, port, &readStream, &writeStream);
+  if (readStream && writeStream) {
+
+    CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
+    CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
+
+    inputStream = (__bridge NSInputStream *)readStream;
+    [inputStream setDelegate:self];
+    [inputStream scheduleInRunLoop:NSRunLoop.mainRunLoop forMode:NSDefaultRunLoopMode];
+    [inputStream open];
+
+    outputStream = (__bridge NSOutputStream *)writeStream;
+    [outputStream setDelegate:self];
+    [outputStream scheduleInRunLoop:NSRunLoop.mainRunLoop forMode:NSDefaultRunLoopMode];
+    [outputStream open];
+  }
+  else {
+
+    if (readStream) {
+      CFRelease(readStream);
+    }
+
+    if (writeStream) {
+      CFRelease(writeStream);
+    }
+
+    return nil;
+  }
+
+  return [super initWithInputStream:inputStream outputStream:outputStream];
+}
+
+@end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/TTransport.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/TTransport.h b/lib/cocoa/src/transport/TTransport.h
index 83aad9e..558cf60 100644
--- a/lib/cocoa/src/transport/TTransport.h
+++ b/lib/cocoa/src/transport/TTransport.h
@@ -17,20 +17,32 @@
  * under the License.
  */
 
+#import <Foundation/Foundation.h>
+
+
+NS_ASSUME_NONNULL_BEGIN
+
+
 @protocol TTransport <NSObject>
 
-  /**
-   * Guarantees that all of len bytes are read
-   *
-   * @param buf Buffer to read into
-   * @param offset Index in buffer to start storing bytes at
-   * @param length Maximum number of bytes to read
-   * @return The number of bytes actually read, which must be equal to len
-   * @throws TTransportException if there was an error reading data
-   */
-- (size_t) readAll: (uint8_t *) buf offset: (size_t) offset length: (size_t) length;
+/**
+ * Guarantees that all of len bytes are read
+ *
+ * @param buf Buffer to read into
+ * @param off Index in buffer to start storing bytes at
+ * @param len Maximum number of bytes to read
+ * @return YES if succeeded, NO if failed
+ * @throws TTransportError if there was an error reading data
+ */
+-(BOOL) readAll:(UInt8 *)buf offset:(UInt32)off length:(UInt32)len error:(NSError *__autoreleasing *)error;
+
+-(UInt32) readAvail:(UInt8 *)buf offset:(UInt32)off maxLength:(UInt32)maxLen error:(NSError *__autoreleasing *)error;
+
+-(BOOL) write:(const UInt8 *)data offset:(UInt32)offset length:(UInt32)length error:(NSError *__autoreleasing *)error;
 
-- (void) write: (const uint8_t *) data offset: (size_t) offset length: (size_t) length;
+-(BOOL) flush:(NSError *__autoreleasing *)error;
 
-- (void) flush;
 @end
+
+
+NS_ASSUME_NONNULL_END

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/TTransportError.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/TTransportError.h b/lib/cocoa/src/transport/TTransportError.h
new file mode 100644
index 0000000..c8c9f06
--- /dev/null
+++ b/lib/cocoa/src/transport/TTransportError.h
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#import "TError.h"
+
+
+extern NSString *TTransportErrorDomain;
+
+
+typedef NS_ENUM (int, TTransportError) {
+  TTransportErrorUnknown        = 0,
+  TTransportErrorNotOpen        = 1,
+  TTransportErrorAlreadyOpen    = 2,
+  TTransportErrorTimedOut       = 3,
+  TTransportErrorEndOfFile      = 4,
+};
+
+
+extern NSString *TTransportErrorExtendedErrorKey;
+extern NSString *TTransportErrorHttpErrorKey;
+
+
+typedef NS_ENUM(int, THttpTransportError) {
+  THttpTransportErrorInvalidResponse  = 1001,
+  THttpTransportErrorInvalidStatus    = 1002,
+  THttpTransportErrorAuthentication   = 1003,
+};

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/TTransportError.m
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/TTransportError.m b/lib/cocoa/src/transport/TTransportError.m
new file mode 100644
index 0000000..b1af076
--- /dev/null
+++ b/lib/cocoa/src/transport/TTransportError.m
@@ -0,0 +1,27 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#import "TTransportError.h"
+
+
+NSString *TTransportErrorDomain = @"TTransportErrorDomain";
+
+
+NSString *TTransportErrorExtendedErrorKey = @"extendedError";
+NSString *TTransportErrorHttpErrorKey = @"httpError";

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/TTransportException.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/TTransportException.h b/lib/cocoa/src/transport/TTransportException.h
deleted file mode 100644
index 6749fe2..0000000
--- a/lib/cocoa/src/transport/TTransportException.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#import "TException.h"
-
-@interface TTransportException : TException {
-}
-
-+ (id) exceptionWithReason: (NSString *) reason
-                     error: (NSError *) error;
-
-+ (id) exceptionWithReason: (NSString *) reason;
-
-@end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/TTransportException.m
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/TTransportException.m b/lib/cocoa/src/transport/TTransportException.m
deleted file mode 100644
index 43cdfbd..0000000
--- a/lib/cocoa/src/transport/TTransportException.m
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#import "TTransportException.h"
-#import "TObjective-C.h"
-
-@implementation TTransportException
-
-+ (id) exceptionWithReason: (NSString *) reason
-                     error: (NSError *) error
-{
-  NSDictionary * userInfo = nil;
-  if (error != nil) {
-    userInfo = [NSDictionary dictionaryWithObject: error forKey: @"error"];
-  }
-
-  return [super exceptionWithName: @"TTransportException"
-                           reason: reason
-                         userInfo: userInfo];
-}
-
-
-+ (id) exceptionWithReason: (NSString *) reason
-{
-  return [self exceptionWithReason: reason error: nil];
-}
-
-@end


[4/7] thrift git commit: THRIFT-2905 Cocoa compiler should have option to produce "modern" Objective-C Client: Cocoa (ObjectiveC & Swift) Author: Kevin Wooten

Posted by je...@apache.org.
http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/TEnum.swift
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/TEnum.swift b/lib/cocoa/src/TEnum.swift
new file mode 100644
index 0000000..562a53a
--- /dev/null
+++ b/lib/cocoa/src/TEnum.swift
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import Foundation
+
+
+public protocol TEnum : TSerializable {
+  
+}
+
+public extension TEnum {
+  
+  public static var thriftType : TType { return TType.I32 }
+  
+}

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/TError.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/TError.h b/lib/cocoa/src/TError.h
new file mode 100644
index 0000000..abb72c7
--- /dev/null
+++ b/lib/cocoa/src/TError.h
@@ -0,0 +1,23 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#import <Foundation/Foundation.h>
+
+
+extern NSString *TErrorDomain;

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/TError.m
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/TError.m b/lib/cocoa/src/TError.m
new file mode 100644
index 0000000..df7f92d
--- /dev/null
+++ b/lib/cocoa/src/TError.m
@@ -0,0 +1,23 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#import "TError.h"
+
+
+NSString *TErrorDomain = @"TErrorDomain";

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/TException.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/TException.h b/lib/cocoa/src/TException.h
deleted file mode 100644
index e56f4fa..0000000
--- a/lib/cocoa/src/TException.h
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#import <Foundation/Foundation.h>
-
-@interface TException : NSException {
-}
-
-+ (id) exceptionWithName: (NSString *) name;
-
-+ (id) exceptionWithName: (NSString *) name
-                  reason: (NSString *) reason;
-
-+ (id) exceptionWithName: (NSString *) name
-                  reason: (NSString *) reason
-                   error: (NSError *) error;
-
-@end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/TException.m
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/TException.m b/lib/cocoa/src/TException.m
deleted file mode 100644
index 0160e3b..0000000
--- a/lib/cocoa/src/TException.m
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#import "TException.h"
-#import "TObjective-C.h"
-
-@implementation TException
-
-+ (id) exceptionWithName: (NSString *) name
-{
-  return [self exceptionWithName: name reason: @"unknown" error: nil];
-}
-
-
-+ (id) exceptionWithName: (NSString *) name
-                  reason: (NSString *) reason
-{
-  return [self exceptionWithName: name reason: reason error: nil];
-}
-
-
-+ (id) exceptionWithName: (NSString *) name
-                  reason: (NSString *) reason
-                   error: (NSError *) error
-{
-  NSDictionary * userInfo = nil;
-  if (error != nil) {
-    userInfo = [NSDictionary dictionaryWithObject: error forKey: @"error"];
-  }
-
-  return [super exceptionWithName: name
-                reason: reason
-                userInfo: userInfo];
-}
-
-
-- (NSString *) description
-{
-  NSMutableString * result = [NSMutableString stringWithString: [self name]];
-  [result appendFormat: @": %@", [self reason]];
-  if ([self userInfo] != nil) {
-    [result appendFormat: @"\n  userInfo = %@", [self userInfo]];
-  }
-
-  return result;
-}
-
-
-@end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/TList.swift
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/TList.swift b/lib/cocoa/src/TList.swift
new file mode 100644
index 0000000..005bd81
--- /dev/null
+++ b/lib/cocoa/src/TList.swift
@@ -0,0 +1,148 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import Foundation
+
+
+
+public struct TList<Element : TSerializable> : MutableCollectionType, Hashable, ArrayLiteralConvertible, TSerializable {
+  
+  public static var thriftType : TType { return .LIST }
+  
+  typealias Storage = Array<Element>
+
+  public typealias Index = Storage.Index
+  
+  private var storage = Storage()
+  
+  public var startIndex : Index {
+    return storage.startIndex
+  }
+  
+  public var endIndex : Index {
+    return storage.endIndex
+  }
+
+  public subscript (position: Index) -> Element {
+    get {
+      return storage[position]
+    }
+    set {
+      storage[position] = newValue
+    }
+  }
+  
+  public var hashValue : Int {
+    let prime = 31
+    var result = 1
+    for element in storage {
+      result = prime * result + element.hashValue
+    }
+    return result
+  }
+  
+  public init(arrayLiteral elements: Element...) {
+    self.storage = Storage(storage)
+  }
+  
+  public init() {
+    self.storage = Storage()
+  }
+  
+  public mutating func append(newElement: Element) {
+    self.storage.append(newElement)
+  }
+  
+  public mutating func appendContentsOf<C : CollectionType where C.Generator.Element == Element>(newstorage: C) {
+    self.storage.appendContentsOf(newstorage)
+  }
+  
+  public mutating func insert(newElement: Element, atIndex index: Int) {
+    self.storage.insert(newElement, atIndex: index)
+  }
+  
+  public mutating func insertContentsOf<C : CollectionType where C.Generator.Element == Element>(newElements: C, at index: Int) {
+    self.storage.insertContentsOf(newElements, at: index)
+  }
+  
+  public mutating func removeAll(keepCapacity keepCapacity: Bool = true) {
+    self.storage.removeAll(keepCapacity: keepCapacity)
+  }
+  
+  public mutating func removeAtIndex(index: Index) {
+    self.storage.removeAtIndex(index)
+  }
+  
+  public mutating func removeFirst(n: Int = 0) {
+    self.storage.removeFirst(n)
+  }
+  
+  public mutating func removeLast() -> Element {
+    return self.storage.removeLast()
+  }
+  
+  public mutating func removeRange(subRange: Range<Index>) {
+    self.storage.removeRange(subRange)
+  }
+  
+  public mutating func reserveCapacity(minimumCapacity: Int) {
+    self.storage.reserveCapacity(minimumCapacity)
+  }
+  
+  public static func readValueFromProtocol(proto: TProtocol) throws -> TList {
+    let (elementType, size) = try proto.readListBegin()
+    if elementType != Element.thriftType {
+      throw NSError(
+        domain: TProtocolErrorDomain,
+        code: Int(TProtocolError.InvalidData.rawValue),
+        userInfo: [TProtocolErrorExtendedErrorKey: NSNumber(int: TProtocolExtendedError.UnexpectedType.rawValue)])
+    }
+    var list = TList()
+    for _ in 0..<size {
+      let element = try Element.readValueFromProtocol(proto)
+      list.storage.append(element)
+    }
+    try proto.readListEnd()
+    return list
+  }
+  
+  public static func writeValue(value: TList, toProtocol proto: TProtocol) throws {
+    try proto.writeListBeginWithElementType(Element.thriftType, size: value.count)
+    for element in value.storage {
+      try Element.writeValue(element, toProtocol: proto)
+    }
+    try proto.writeListEnd()
+  }
+}
+
+extension TList : CustomStringConvertible, CustomDebugStringConvertible {
+  
+  public var description : String {
+    return storage.description
+  }
+  
+  public var debugDescription : String {
+    return storage.debugDescription
+  }
+  
+}
+
+public func ==<Element>(lhs: TList<Element>, rhs: TList<Element>) -> Bool {
+  return lhs.storage == rhs.storage
+}

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/TMap.swift
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/TMap.swift b/lib/cocoa/src/TMap.swift
new file mode 100644
index 0000000..e96e747
--- /dev/null
+++ b/lib/cocoa/src/TMap.swift
@@ -0,0 +1,158 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import Foundation
+
+
+public struct TMap<Key : TSerializable, Value : TSerializable> : CollectionType, DictionaryLiteralConvertible, TSerializable {
+  
+  public static var thriftType : TType { return .MAP }
+
+  typealias Storage = Dictionary<Key, Value>
+
+  public typealias Index = Storage.Index
+
+  public typealias Element = Storage.Element
+  
+  private var storage : Storage
+
+  public var startIndex : Index {
+    return storage.startIndex
+  }
+  
+  public var endIndex: Index {
+    return storage.endIndex
+  }
+
+  public var keys: LazyMapCollection<[Key : Value], Key> {
+    return storage.keys
+  }
+  
+  public var values: LazyMapCollection<[Key : Value], Value> {
+    return storage.values
+  }
+  
+  public init() {
+    storage = Storage()
+  }
+  
+  public init(dictionaryLiteral elements: (Key, Value)...) {
+    storage = Storage()
+    for (key, value) in elements {
+      storage[key] = value
+    }
+  }
+  
+  public init(minimumCapacity: Int) {
+    storage = Storage(minimumCapacity: minimumCapacity)
+  }
+  
+  public subscript (position: Index) -> Element {
+    get {
+      return storage[position]
+    }
+  }
+  
+  public func indexForKey(key: Key) -> Index? {
+    return storage.indexForKey(key)
+  }
+  
+  public subscript (key: Key) -> Value? {
+    get {
+      return storage[key]
+    }
+    set {
+      storage[key] = newValue
+    }
+  }
+
+  public mutating func updateValue(value: Value, forKey key: Key) -> Value? {
+    return updateValue(value, forKey: key)
+  }
+  
+  public mutating func removeAtIndex(index: DictionaryIndex<Key, Value>) -> (Key, Value) {
+    return removeAtIndex(index)
+  }
+  
+  public mutating func removeValueForKey(key: Key) -> Value? {
+    return storage.removeValueForKey(key)
+  }
+  
+  public mutating func removeAll(keepCapacity keepCapacity: Bool = false) {
+    storage.removeAll(keepCapacity: keepCapacity)
+  }
+
+  public var hashValue : Int {
+    let prime = 31
+    var result = 1
+    for (key, value) in storage {
+      result = prime * result + key.hashValue
+      result = prime * result + value.hashValue
+    }
+    return result
+  }
+  
+  public static func readValueFromProtocol(proto: TProtocol) throws -> TMap {
+    let (keyType, valueType, size) = try proto.readMapBegin()
+    if keyType != Key.thriftType || valueType != Value.thriftType {
+      throw NSError(
+        domain: TProtocolErrorDomain,
+        code: Int(TProtocolError.InvalidData.rawValue),
+        userInfo: [TProtocolErrorExtendedErrorKey: NSNumber(int: TProtocolExtendedError.UnexpectedType.rawValue)])
+    }
+    var map = TMap()
+    for _ in 0..<size {
+      let key = try Key.readValueFromProtocol(proto)
+      let value = try Value.readValueFromProtocol(proto)
+      map.storage[key] = value
+    }
+    try proto.readMapEnd()
+    return map
+  }
+  
+  public static func writeValue(value: TMap, toProtocol proto: TProtocol) throws {
+    try proto.writeMapBeginWithKeyType(Key.thriftType, valueType: Value.thriftType, size: value.count)
+    for (key, value) in value.storage {
+      try Key.writeValue(key, toProtocol: proto)
+      try Value.writeValue(value, toProtocol: proto)
+    }
+    try proto.writeMapEnd()
+  }
+  
+}
+
+
+extension TMap : CustomStringConvertible, CustomDebugStringConvertible {
+  
+  public var description : String {
+    return storage.description
+  }
+  
+  public var debugDescription : String {
+    return storage.debugDescription
+  }
+  
+}
+
+public func ==<Key, Value>(lhs: TMap<Key,Value>, rhs: TMap<Key, Value>) -> Bool {
+  if lhs.count != rhs.count {
+    return false
+  }
+  return lhs.storage == rhs.storage
+}

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/TObjective-C.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/TObjective-C.h b/lib/cocoa/src/TObjective-C.h
deleted file mode 100644
index 9c0831d..0000000
--- a/lib/cocoa/src/TObjective-C.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-/*
- * TObjective-C.h is for supporting coexistence of both the ARC (Automatic 
- * Reference Counting) mode and the Non-ARC mode of Objective-C 
- * in the same source code.
- *
- *                  2011/11/14  HIRANO Satoshi (AIST, Japan)
- *
- * Before:
- *
- *    var = [aObject retain];
- *    [aObject release];
- *    [aObject autorelease];
- *    [super dealloc];
- *    CFFunction(obj);
- *
- * ARC and Non-ARC compatible:
- *
- *    #import "TObjective-C.h"
- *    var = [aObject retain_stub];
- *    [aObject release_stub];
- *    [aObject autorelease_stub];
- *    [super dealloc_stub];
- *    CFFunction(bridge_stub obj);
- *
- *    Don't use retain_stub for @property(retain).
- *    Use NSAutoreleasePool like this:
- *        #if __has_feature(objc_arc)
- *          @autoreleasepool {
- *              // code 
- *          }
- *        #else
- *          NSAutoReleasePool *pool = [[NSAutoReleasePool alloc] init...
- *          // code
- *          [pool release];
- *        #endif
- */
-
-
-#if !defined(retain_stub)
-#if __has_feature(objc_arc)
-#define retain_stub self
-#define autorelease_stub self
-#define release_stub self
-#define dealloc_stub self
-#define bridge_stub __bridge
-#else
-#define retain_stub retain
-#define autorelease_stub autorelease
-#define release_stub release
-#define dealloc_stub dealloc
-#define bridge_stub
-#endif
-#endif

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/TProcessor.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/TProcessor.h b/lib/cocoa/src/TProcessor.h
index 980be94..20c72e2 100644
--- a/lib/cocoa/src/TProcessor.h
+++ b/lib/cocoa/src/TProcessor.h
@@ -20,10 +20,16 @@
 #import <Foundation/Foundation.h>
 #import "TProtocol.h"
 
+NS_ASSUME_NONNULL_BEGIN
+
 
 @protocol TProcessor <NSObject>
 
-- (BOOL) processOnInputProtocol: (id <TProtocol>) inProtocol
-                 outputProtocol: (id <TProtocol>) outProtocol;
+-(BOOL) processOnInputProtocol:(id <TProtocol>)inProtocol
+                outputProtocol:(id <TProtocol>)outProtocol
+                         error:(NSError **)error;
 
 @end
+
+
+NS_ASSUME_NONNULL_END

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/TProcessorFactory.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/TProcessorFactory.h b/lib/cocoa/src/TProcessorFactory.h
index 29d12b3..85020a5 100644
--- a/lib/cocoa/src/TProcessorFactory.h
+++ b/lib/cocoa/src/TProcessorFactory.h
@@ -20,8 +20,14 @@
 #import <Foundation/Foundation.h>
 #import "TProcessor.h"
 
+NS_ASSUME_NONNULL_BEGIN
+
+
 @protocol TProcessorFactory <NSObject>
 
-- (id<TProcessor>) processorForTransport: (id<TTransport>) transport;
+-(id<TProcessor>) processorForTransport:(id<TTransport>)transport;
 
 @end
+
+
+NS_ASSUME_NONNULL_END

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/TProtocol.swift
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/TProtocol.swift b/lib/cocoa/src/TProtocol.swift
new file mode 100644
index 0000000..1775849
--- /dev/null
+++ b/lib/cocoa/src/TProtocol.swift
@@ -0,0 +1,190 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import Foundation
+
+
+public extension TProtocol {
+  
+  public func readMessageBegin() throws -> (String, TMessageType, Int) {
+    
+    var name : NSString?
+    var type : Int32 = -1
+    var sequenceID : Int32 = -1
+    
+    try readMessageBeginReturningName(&name, type: &type, sequenceID: &sequenceID)
+    
+    return (name as String!, TMessageType(rawValue: type)!, Int(sequenceID))
+  }
+  
+  public func writeMessageBeginWithName(name: String, type: TMessageType, sequenceID: Int) throws {
+    try writeMessageBeginWithName(name, type: type.rawValue, sequenceID: Int32(sequenceID))
+  }
+  
+  public func readStructBegin() throws -> (String?) {
+    
+    var name : NSString? = nil
+    
+    try readStructBeginReturningName(&name)
+    
+    return (name as String?)
+  }
+  
+  public func readFieldBegin() throws -> (String?, TType, Int) {
+    
+    var name : NSString? = nil
+    var type : Int32 = -1
+    var fieldID : Int32 = -1
+    
+    try readFieldBeginReturningName(&name, type: &type, fieldID: &fieldID)
+    
+    return (name as String?, TType(rawValue: type)!, Int(fieldID))
+  }
+  
+  public func writeFieldBeginWithName(name: String, type: TType, fieldID: Int) throws {
+    try writeFieldBeginWithName(name, type: type.rawValue, fieldID: Int32(fieldID))
+  }
+  
+  public func readMapBegin() throws -> (TType, TType, Int32) {
+    
+    var keyType : Int32 = -1
+    var valueType : Int32 = -1
+    var size : Int32 = 0
+    
+    try readMapBeginReturningKeyType(&keyType, valueType: &valueType, size: &size)
+    
+    return (TType(rawValue: keyType)!, TType(rawValue: valueType)!, size)
+  }
+  
+  public func writeMapBeginWithKeyType(keyType: TType, valueType: TType, size: Int) throws {
+    try writeMapBeginWithKeyType(keyType.rawValue, valueType: valueType.rawValue, size: Int32(size))
+  }
+  
+  public func readSetBegin() throws -> (TType, Int32) {
+    
+    var elementType : Int32 = -1
+    var size : Int32 = 0
+    
+    try readSetBeginReturningElementType(&elementType, size: &size)
+    
+    return (TType(rawValue: elementType)!, size)
+  }
+  
+  public func writeSetBeginWithElementType(elementType: TType, size: Int) throws {
+    try writeSetBeginWithElementType(elementType.rawValue, size: Int32(size))
+  }
+  
+  public func readListBegin() throws -> (TType, Int32) {
+    
+    var elementType : Int32 = -1
+    var size : Int32 = 0
+    
+    try readListBeginReturningElementType(&elementType, size: &size)
+    
+    return (TType(rawValue: elementType)!, size)
+  }
+  
+  public func writeListBeginWithElementType(elementType: TType, size: Int) throws {
+    try writeListBeginWithElementType(elementType.rawValue, size: Int32(size))
+  }
+  
+  public func writeFieldValue<T: TSerializable>(value: T, name: String, type: TType, id: Int32) throws {
+    try writeFieldBeginWithName(name, type: type.rawValue, fieldID: id)
+    try writeValue(value)
+    try writeFieldEnd()
+  }
+  
+  public func readValue<T: TSerializable>() throws -> T {
+    return try T.readValueFromProtocol(self)
+  }
+  
+  public func writeValue<T: TSerializable>(value: T) throws {
+    try T.writeValue(value, toProtocol: self)
+  }
+  
+  public func readResultMessageBegin() throws {
+    
+    let (_, type, _) = try readMessageBegin();
+    
+    if type == .EXCEPTION {
+      let x = try readException()
+      throw x
+    }
+    
+    return
+  }
+  
+  public func validateValue(value: Any?, named name: String) throws {
+    
+    if value == nil {
+      throw NSError(
+        domain: TProtocolErrorDomain,
+        code: Int(TProtocolError.Unknown.rawValue),
+        userInfo: [TProtocolErrorFieldNameKey: name])
+    }
+    
+  }
+  
+  public func readException() throws -> ErrorType {
+    
+    var reason : String?
+    var type = TApplicationError.Unknown
+    
+    try readStructBegin()
+    
+    fields: while (true) {
+      
+      let (_, fieldType, fieldID) = try readFieldBegin()
+      
+      switch (fieldID, fieldType) {
+      case (_, .STOP):
+        break fields
+        
+      case (1, .STRING):
+        reason = try readValue() as String
+        
+      case (2, .I32):
+        let typeVal = try readValue() as Int32
+        if let tmp = TApplicationError(rawValue: typeVal) {
+          type = tmp
+        }
+        
+      case let (_, unknownType):
+        try skipType(unknownType)
+      }
+      
+      try readFieldEnd()
+    }
+    
+    try readStructEnd()
+    
+    return NSError(type:type, reason:reason ?? "")
+  }
+  
+  public func writeExceptionForMessageName(name: String, sequenceID: Int, ex: NSError) throws {
+    try writeMessageBeginWithName(name, type: .EXCEPTION, sequenceID: sequenceID)
+    try ex.write(self)
+    try writeMessageEnd()
+  }
+  
+  public func skipType(type: TType) throws {
+    try TProtocolUtil.skipType(type.rawValue, onProtocol: self)
+  }
+  
+}

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/TSerializable.swift
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/TSerializable.swift b/lib/cocoa/src/TSerializable.swift
new file mode 100644
index 0000000..3fdfd41
--- /dev/null
+++ b/lib/cocoa/src/TSerializable.swift
@@ -0,0 +1,178 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import Foundation
+
+
+public protocol TSerializable : Hashable {
+  
+  static var thriftType : TType { get }
+  
+  init()
+  
+  static func readValueFromProtocol(proto: TProtocol) throws -> Self
+  
+  static func writeValue(value: Self, toProtocol proto: TProtocol) throws
+  
+}
+
+
+
+infix operator ?== {}
+
+public func ?==<T: TSerializable>(lhs: T?, rhs: T?) -> Bool {
+  if let l = lhs, r = rhs {
+    return l == r
+  }
+  return lhs == rhs
+}
+
+public func ?==<T: TSerializable>(lhs: T, rhs: T) -> Bool {
+  return lhs == rhs
+}
+
+
+
+extension Bool : TSerializable {
+  
+  public static let thriftType = TType.BOOL
+  
+  public static func readValueFromProtocol(proto: TProtocol) throws -> Bool {
+    var value : ObjCBool = false
+    try proto.readBool(&value)
+    return value.boolValue
+  }
+  
+  public static func writeValue(value: Bool, toProtocol proto: TProtocol) throws {
+    try proto.writeBool(value)
+  }
+  
+}
+
+extension Int8 : TSerializable {
+  
+  public static let thriftType = TType.BYTE
+  
+  public static func readValueFromProtocol(proto: TProtocol) throws -> Int8 {
+    var value = UInt8()
+    try proto.readByte(&value)
+    return Int8(value)
+  }
+  
+  public static func writeValue(value: Int8, toProtocol proto: TProtocol) throws {
+    try proto.writeByte(UInt8(value))
+  }
+  
+}
+
+extension Int16 : TSerializable {
+  
+  public static let thriftType = TType.I16
+  
+  public static func readValueFromProtocol(proto: TProtocol) throws -> Int16 {
+    var value = Int16()
+    try proto.readI16(&value)
+    return value
+  }
+  
+  public static func writeValue(value: Int16, toProtocol proto: TProtocol) throws {
+    try proto.writeI16(value)
+  }
+  
+}
+
+extension Int : TSerializable {
+  
+  public static let thriftType = TType.I32
+  
+  public static func readValueFromProtocol(proto: TProtocol) throws -> Int {
+    var value = Int32()
+    try proto.readI32(&value)
+    return Int(value)
+  }
+  
+  public static func writeValue(value: Int, toProtocol proto: TProtocol) throws {
+    try proto.writeI32(Int32(value))
+  }
+  
+}
+
+extension Int32 : TSerializable {
+  
+  public static let thriftType = TType.I32
+  
+  public static func readValueFromProtocol(proto: TProtocol) throws -> Int32 {
+    var value = Int32()
+    try proto.readI32(&value)
+    return value
+  }
+  
+  public static func writeValue(value: Int32, toProtocol proto: TProtocol) throws {
+    try proto.writeI32(value)
+  }
+  
+}
+
+extension Int64 : TSerializable {
+  
+  public static let thriftType = TType.I64
+  
+  public static func readValueFromProtocol(proto: TProtocol) throws -> Int64 {
+    var value = Int64()
+    try proto.readI64(&value)
+    return value
+  }
+  
+  public static func writeValue(value: Int64, toProtocol proto: TProtocol) throws {
+    try proto.writeI64(value)
+  }
+  
+}
+
+extension Double : TSerializable {
+  
+  public static let thriftType = TType.DOUBLE
+  
+  public static func readValueFromProtocol(proto: TProtocol) throws -> Double {
+    var value = Double()
+    try proto.readDouble(&value)
+    return value
+  }
+  
+  public static func writeValue(value: Double, toProtocol proto: TProtocol) throws {
+    try proto.writeDouble(value)
+  }
+  
+}
+
+extension String : TSerializable {
+  
+  public static let thriftType = TType.STRING
+  
+  public static func readValueFromProtocol(proto: TProtocol) throws -> String {
+    var value : NSString?
+    try proto.readString(&value)
+    return value as! String
+  }
+  
+  public static func writeValue(value: String, toProtocol proto: TProtocol) throws {
+    try proto.writeString(value)
+  }
+  
+}

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/TSet.swift
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/TSet.swift b/lib/cocoa/src/TSet.swift
new file mode 100644
index 0000000..85833e5
--- /dev/null
+++ b/lib/cocoa/src/TSet.swift
@@ -0,0 +1,161 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import Foundation
+
+
+public struct TSet<Element : TSerializable> : CollectionType, ArrayLiteralConvertible, TSerializable {
+  
+  public static var thriftType : TType { return .SET }
+  
+  public typealias Index = Storage.Index
+  
+  typealias Storage = Set<Element>
+  
+  private var storage : Storage
+  
+  public init() {
+    storage = Storage()
+  }
+  
+  public init(arrayLiteral elements: Element...) {
+    storage = Storage(elements)
+  }
+  
+  public init<S : SequenceType where S.Generator.Element == Element>(_ sequence: S) {
+    storage = Storage(sequence)    
+  }
+  
+  public var startIndex : Index { return storage.startIndex }
+  
+  public var endIndex : Index { return storage.endIndex }
+  
+  public mutating func insert(member: Element) {
+    return storage.insert(member)
+  }
+  
+  public mutating func remove(element: Element) -> Element? {
+    return storage.remove(element)
+  }
+  
+  public mutating func removeAll(keepCapacity keepCapacity: Bool = false) {
+    return storage.removeAll(keepCapacity: keepCapacity)
+  }
+  
+  public mutating func removeAtIndex(index: SetIndex<Element>) -> Element {
+    return storage.removeAtIndex(index)
+  }
+  
+  public subscript (position: SetIndex<Element>) -> Element {
+    return storage[position]
+  }
+  
+  public func union(other: TSet) -> TSet {
+    return TSet(storage.union(other))
+  }
+  
+  public func intersect(other: TSet) -> TSet {
+    return TSet(storage.intersect(other))
+  }
+  
+  public func exclusiveOr(other: TSet) -> TSet {
+    return TSet(storage.exclusiveOr(other))
+  }
+  
+  public func subtract(other: TSet) -> TSet {
+    return TSet(storage.subtract(other))
+  }
+  
+  public mutating func intersectInPlace(other: TSet) {
+    storage.intersectInPlace(other)
+  }
+
+  public mutating func exclusiveOrInPlace(other: TSet) {
+    storage.exclusiveOrInPlace(other)
+  }
+
+  public mutating func subtractInPlace(other: TSet) {
+    storage.subtractInPlace(other)
+  }  
+
+  public func isSubsetOf(other: TSet) -> Bool {
+    return storage.isSubsetOf(other)
+  }
+
+  public func isDisjointWith(other: TSet) -> Bool {
+    return storage.isDisjointWith(other)
+  }
+  
+  public func isSupersetOf(other: TSet) -> Bool {
+    return storage.isSupersetOf(other)
+  }
+
+  public var isEmpty: Bool { return storage.isEmpty }
+
+  public var hashValue : Int {
+    let prime = 31
+    var result = 1
+    for element in storage {
+      result = prime * result + element.hashValue
+    }
+    return result
+  }
+  
+  public static func readValueFromProtocol(proto: TProtocol) throws -> TSet {
+    let (elementType, size) = try proto.readSetBegin()
+    if elementType != Element.thriftType {
+      throw NSError(
+        domain: TProtocolErrorDomain,
+        code: Int(TProtocolError.InvalidData.rawValue),
+        userInfo: [TProtocolErrorExtendedErrorKey: NSNumber(int: elementType.rawValue)])
+    }
+    var set = TSet()
+    for _ in 0..<size {
+      let element = try Element.readValueFromProtocol(proto)
+      set.storage.insert(element)
+    }
+    try proto.readSetEnd()
+    return set
+  }
+  
+  public static func writeValue(value: TSet, toProtocol proto: TProtocol) throws {
+    try proto.writeSetBeginWithElementType(Element.thriftType, size: value.count)
+    for element in value.storage {
+      try Element.writeValue(element, toProtocol: proto)
+    }
+    try proto.writeSetEnd()
+  }
+  
+}
+
+extension TSet : CustomStringConvertible, CustomDebugStringConvertible {
+  
+  public var description : String {
+    return storage.description
+  }
+  
+  public var debugDescription : String {
+    return storage.debugDescription
+  }
+  
+}
+
+public func ==<Element>(lhs: TSet<Element>, rhs: TSet<Element>) -> Bool {
+  return lhs.storage == rhs.storage
+}

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/TSharedProcessorFactory.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/TSharedProcessorFactory.h b/lib/cocoa/src/TSharedProcessorFactory.h
index cf4a462..c75fad1 100644
--- a/lib/cocoa/src/TSharedProcessorFactory.h
+++ b/lib/cocoa/src/TSharedProcessorFactory.h
@@ -20,8 +20,9 @@
 #import <Foundation/Foundation.h>
 #import "TProcessorFactory.h"
 
-@interface TSharedProcessorFactory : NSObject <TProcessorFactory> {
-  id<TProcessor> mSharedProcessor;
-}
-- (id) initWithSharedProcessor: (id<TProcessor>) sharedProcessor;
+
+@interface TSharedProcessorFactory : NSObject <TProcessorFactory>
+
+-(id) initWithSharedProcessor:(id<TProcessor>)sharedProcessor;
+
 @end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/TSharedProcessorFactory.m
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/TSharedProcessorFactory.m b/lib/cocoa/src/TSharedProcessorFactory.m
index a0007c0..3d55f47 100644
--- a/lib/cocoa/src/TSharedProcessorFactory.m
+++ b/lib/cocoa/src/TSharedProcessorFactory.m
@@ -19,34 +19,31 @@
 
 
 #import "TSharedProcessorFactory.h"
-#import "TObjective-C.h"
+
+
+@interface TSharedProcessorFactory ()
+
+@property(strong, nonatomic) id<TProcessor> sharedProcessor;
+
+@end
 
 
 @implementation TSharedProcessorFactory
 
 
-- (id) initWithSharedProcessor: (id<TProcessor>) sharedProcessor
+-(id) initWithSharedProcessor:(id<TProcessor>)sharedProcessor
 {
   self = [super init];
-  if (!self) {
-    return nil;
+  if (self) {
+    _sharedProcessor = sharedProcessor;
   }
-  
-  mSharedProcessor = [sharedProcessor retain_stub];
-  return self;
-}
-
 
-- (void) dealloc
-{
-  [mSharedProcessor release_stub];
-  [super dealloc_stub];
+  return self;
 }
 
-
-- (id<TProcessor>) processorForTransport: (id<TTransport>) transport
+-(id<TProcessor>) processorForTransport:(id<TTransport>)transport
 {
-  return [[mSharedProcessor retain_stub] autorelease_stub];
+  return _sharedProcessor;
 }
 
 @end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/TStruct.swift
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/TStruct.swift b/lib/cocoa/src/TStruct.swift
new file mode 100644
index 0000000..cea72e7
--- /dev/null
+++ b/lib/cocoa/src/TStruct.swift
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import Foundation
+
+
+public protocol TStruct : TSerializable {
+}
+
+
+public extension TStruct {
+  
+  public static var thriftType : TType { return TType.STRUCT }
+  
+}

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/protocol/TBase.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/protocol/TBase.h b/lib/cocoa/src/protocol/TBase.h
index 33037ef..b31061e 100644
--- a/lib/cocoa/src/protocol/TBase.h
+++ b/lib/cocoa/src/protocol/TBase.h
@@ -26,16 +26,21 @@
 /**
  * De-serialize object from the given input protocol
  *
- * @param input protocol used for reading 
+ * @param input protocol used for reading
  */
-- (void) read: (id <TProtocol>) inProtocol;
+-(BOOL) read:(id <TProtocol>)inProtocol error:(NSError **)error;
 
 /**
  * Serialize object to the given protocol
  *
  * @param buf output protocol used for writing
  */
-- (void) write: (id <TProtocol>) outProtocol;
+-(BOOL) write:(id <TProtocol>)outProtocol error:(NSError **)error;
 
-@end
 
+/**
+ * Validate required fields
+ */
+-(BOOL) validate:(NSError *__autoreleasing *)__thriftError;
+
+@end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/protocol/TBinaryProtocol.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/protocol/TBinaryProtocol.h b/lib/cocoa/src/protocol/TBinaryProtocol.h
index 9a73730..bb90fad 100644
--- a/lib/cocoa/src/protocol/TBinaryProtocol.h
+++ b/lib/cocoa/src/protocol/TBinaryProtocol.h
@@ -21,31 +21,29 @@
 #import "TTransport.h"
 #import "TProtocolFactory.h"
 
+NS_ASSUME_NONNULL_BEGIN
 
-@interface TBinaryProtocol : NSObject <TProtocol> {
-  id <TTransport> mTransport;
-  BOOL mStrictRead;
-  BOOL mStrictWrite;
-  int32_t mMessageSizeLimit;
-}
 
-- (id) initWithTransport: (id <TTransport>) transport;
+@interface TBinaryProtocol : NSObject <TProtocol>
 
-- (id) initWithTransport: (id <TTransport>) transport
-              strictRead: (BOOL) strictRead
-             strictWrite: (BOOL) strictWrite;
+@property (assign, nonatomic) UInt32 messageSizeLimit;
 
-- (int32_t) messageSizeLimit;
-- (void) setMessageSizeLimit: (int32_t) sizeLimit;
+-(id) initWithTransport:(id <TTransport>)transport;
 
-@end
+-(id) initWithTransport:(id <TTransport>)transport
+             strictRead:(BOOL)strictRead
+            strictWrite:(BOOL)strictWrite;
+
+@end;
 
 
-@interface TBinaryProtocolFactory : NSObject <TProtocolFactory> {
-}
+@interface TBinaryProtocolFactory : NSObject <TProtocolFactory>
 
-+ (TBinaryProtocolFactory *) sharedFactory;
++(TBinaryProtocolFactory *) sharedFactory;
 
-- (TBinaryProtocol *) newProtocolOnTransport: (id <TTransport>) transport;
+-(TBinaryProtocol *) newProtocolOnTransport:(id <TTransport>)transport;
 
 @end
+
+
+NS_ASSUME_NONNULL_END
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/protocol/TBinaryProtocol.m
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/protocol/TBinaryProtocol.m b/lib/cocoa/src/protocol/TBinaryProtocol.m
index 847c723..1f9e57a 100644
--- a/lib/cocoa/src/protocol/TBinaryProtocol.m
+++ b/lib/cocoa/src/protocol/TBinaryProtocol.m
@@ -18,63 +18,20 @@
  */
 
 #import "TBinaryProtocol.h"
-#import "TProtocolException.h"
-#import "TObjective-C.h"
+#import "TProtocolError.h"
 
-/* In the modern protocol, version is stored in the high half of an int32.
- * The low half contains type info. */
-static const uint16_t VERSION_1 = 0x8001;
 
-NS_INLINE size_t
-CheckedCastInt32ToSizeT(int32_t size)
-{
-  if (size < 0) {
-    NSString *reason = [NSString stringWithFormat:
-                        @"%s: refusing to read data with negative size: %"PRId32,
-                        __func__, size];
-    @throw [TProtocolException
-            exceptionWithName: @"TProtocolException"
-            reason: reason];
-  }
-  size_t checkedSize = (size_t)size;
-  return checkedSize;
-}
+static SInt32 VERSION_1 = 0x80010000;
+static SInt32 VERSION_MASK = 0xffff0000;
 
-NS_INLINE int32_t
-CheckedCastSizeTToInt32(size_t size)
-{
-  if (size > INT32_MAX) {
-    NSString *reason = [NSString stringWithFormat:
-                        @"%s: data size exceeds values representable by a 32-bit signed integer: %zu",
-                        __func__, size];
-    @throw [TProtocolException
-            exceptionWithName: @"TProtocolException"
-            reason: reason];
-  }
-  int32_t checkedSize = (int32_t)size;
-  return checkedSize;
-}
 
-NS_INLINE uint8_t
-CheckedCastIntToUInt8(int size)
-{
-  if (size > UINT8_MAX) {
-    NSString *reason = [NSString stringWithFormat:
-                        @"%s: data size exceeds values representable by a 8-bit unsigned integer: %d",
-                        __func__, size];
-    @throw [TProtocolException
-            exceptionWithName: @"TProtocolException"
-            reason: reason];
-  }
-  uint8_t checkedSize = (uint8_t)size;
-  return checkedSize;
-}
+static TBinaryProtocolFactory *gSharedFactory = nil;
 
-static TBinaryProtocolFactory * gSharedFactory = nil;
 
 @implementation TBinaryProtocolFactory
 
-+ (TBinaryProtocolFactory *) sharedFactory {
++(TBinaryProtocolFactory *) sharedFactory
+{
   if (gSharedFactory == nil) {
     gSharedFactory = [[TBinaryProtocolFactory alloc] init];
   }
@@ -82,363 +39,553 @@ static TBinaryProtocolFactory * gSharedFactory = nil;
   return gSharedFactory;
 }
 
-- (TBinaryProtocol *) newProtocolOnTransport: (id <TTransport>) transport {
-  return [[TBinaryProtocol alloc] initWithTransport: transport];
+-(NSString *) protocolName
+{
+  return @"binary";
+}
+
+-(TBinaryProtocol *) newProtocolOnTransport:(id <TTransport>)transport
+{
+  return [[TBinaryProtocol alloc] initWithTransport:transport];
 }
 
 @end
 
 
+@interface TBinaryProtocol ()
+
+@property(strong, nonatomic) id <TTransport> transport;
+
+@property(assign, nonatomic) BOOL strictRead;
+@property(assign, nonatomic) BOOL strictWrite;
+
+@property(strong, nonatomic) NSString *currentMessageName;
+@property(strong, nonatomic) NSString *currentFieldName;
+
+@end
+
 
 @implementation TBinaryProtocol
 
-- (id) initWithTransport: (id <TTransport>) transport
+-(id) initWithTransport:(id <TTransport>)aTransport
 {
-  return [self initWithTransport: transport strictRead: NO strictWrite: YES];
+  return [self initWithTransport:aTransport strictRead:NO strictWrite:YES];
 }
 
-- (id) initWithTransport: (id <TTransport>) transport
-              strictRead: (BOOL) strictRead
-             strictWrite: (BOOL) strictWrite
+-(id) initWithTransport:(id <TTransport>)transport
+             strictRead:(BOOL)strictRead
+            strictWrite:(BOOL)strictWrite
 {
   self = [super init];
-  mTransport = [transport retain_stub];
-  mStrictRead = strictRead;
-  mStrictWrite = strictWrite;
+  if (self) {
+    _transport = transport;
+    _strictRead = strictRead;
+    _strictWrite = strictWrite;
+  }
   return self;
 }
 
-
-- (int32_t) messageSizeLimit
-{
-  return mMessageSizeLimit;
-}
-
-
-- (void) setMessageSizeLimit: (int32_t) sizeLimit
+-(id <TTransport>) transport
 {
-  mMessageSizeLimit = sizeLimit;
+  return _transport;
 }
 
-
-- (void) dealloc
+-(NSString *) readStringBody:(int)size error:(NSError **)error
 {
-  [mTransport release_stub];
-  [super dealloc_stub];
-}
+  NSMutableData *data = [NSMutableData dataWithLength:size];
+  if (!data) {
+    PROTOCOL_ERROR(nil, Unknown, @"Unable to allocate %d bytes", size);
+  }
 
+  if (![_transport readAll:data.mutableBytes offset:0 length:size error:error]) {
+    PROTOCOL_TRANSPORT_ERROR(nil, error, @"Transport read failed");
+  }
 
-- (id <TTransport>) transport
-{
-  return mTransport;
+  return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
 }
 
 
-- (NSString *) readStringBody: (int) rawSize
+-(BOOL) readMessageBeginReturningName:(NSString **)name
+                                 type:(SInt32 *)type
+                           sequenceID:(SInt32 *)sequenceID
+                                error:(NSError *__autoreleasing *)error
 {
-  size_t size = CheckedCastInt32ToSizeT(rawSize);
-  char * buffer = malloc(size+1);
-  if (!buffer) {
-    @throw [TProtocolException exceptionWithName: @"TProtocolException"
-                                          reason: [NSString stringWithFormat: @"Unable to allocate memory in %s, size: %zu",
-                                                   __PRETTY_FUNCTION__,
-                                                   size]];;
+  SInt32 size;
+  if (![self readI32:&size error:error]) {
+    return NO;
   }
-  [mTransport readAll: (uint8_t *) buffer offset: 0 length: size];
-  buffer[size] = 0;
-  NSString * result = [NSString stringWithUTF8String: buffer];
-  free(buffer);
-  return result;
-}
-
+  ;
 
-- (void) readMessageBeginReturningName: (NSString **) name
-                                  type: (int *) type
-                            sequenceID: (int *) sequenceID
-{
-  int32_t size = [self readI32];
   if (size < 0) {
-    /* Version (unsigned) is stored in the high halfword. */
-    uint16_t version = (size >> 16) & 0xFFFF;
+    int version = size & VERSION_MASK;
     if (version != VERSION_1) {
-      NSString *reason = [NSString stringWithFormat:
-                          @"%s: Expected version %"PRIu16", instead found: %"PRIu16,
-                          __func__, VERSION_1, version];
-      @throw [TProtocolException exceptionWithName: @"TProtocolException"
-                                 reason: reason];
+      PROTOCOL_ERROR(NO, BadVersion, @"Bad message version");
     }
     if (type != NULL) {
       *type = size & 0x00FF;
     }
-    NSString * messageName = [self readString];
-    if (name != NULL) {
+    NSString *messageName;
+    if (![self readString:&messageName error:error]) {
+      return NO;
+    }
+    if (name != nil) {
       *name = messageName;
     }
-    int seqID = [self readI32];
-    if (sequenceID != NULL) {
-      *sequenceID = seqID;
+  }
+  else {
+
+    if (_strictRead) {
+      PROTOCOL_ERROR(NO, InvalidData, @"Missing message version, old client?");
     }
-  } else {
-    if (mStrictRead) {
-      @throw [TProtocolException exceptionWithName: @"TProtocolException"
-                                 reason: @"Missing version in readMessageBegin, old client?"];
+
+    if (_messageSizeLimit > 0 && size > _messageSizeLimit) {
+      PROTOCOL_ERROR(NO, SizeLimit, @"Message exceeeds size limit of %d", (int)size);
     }
-    if ([self messageSizeLimit] > 0 && size > [self messageSizeLimit]) {
-      @throw [TProtocolException exceptionWithName: @"TProtocolException"
-                                            reason: [NSString stringWithFormat: @"Message too big.  Size limit is: %d Message size is: %d",
-                                                     mMessageSizeLimit,
-                                                     size]];
+
+    NSString *messageName = [self readStringBody:size error:error];
+    if (!messageName) {
+      return NO;
     }
-    NSString * messageName = [self readStringBody: size];
+
     if (name != NULL) {
       *name = messageName;
     }
-    int messageType = [self readByte];
+
+    UInt8 messageType;
+    if (![self readByte:&messageType error:error]) {
+      return NO;
+    }
+
     if (type != NULL) {
       *type = messageType;
     }
-    int seqID = [self readI32];
-    if (sequenceID != NULL) {
-      *sequenceID = seqID;
-    }
   }
+
+  SInt32 seqID;
+  if (![self readI32:&seqID error:error]) {
+    return NO;
+  }
+  if (sequenceID != NULL) {
+    *sequenceID = seqID;
+  }
+
+  return YES;
 }
 
 
-- (void) readMessageEnd {}
+-(BOOL) readMessageEnd:(NSError *__autoreleasing *)error
+{
+  return YES;
+}
 
 
-- (void) readStructBeginReturningName: (NSString **) name
+-(BOOL) readStructBeginReturningName:(NSString *__autoreleasing *)name error:(NSError *__autoreleasing *)error
 {
-  if (name != NULL) {
-    *name = nil;
-  }
+  return YES;
 }
 
 
-- (void) readStructEnd {}
+-(BOOL) readStructEnd:(NSError *__autoreleasing *)error
+{
+  return YES;
+}
 
 
-- (void) readFieldBeginReturningName: (NSString **) name
-                                type: (int *) fieldType
-                             fieldID: (int *) fieldID
+-(BOOL) readFieldBeginReturningName:(NSString *__autoreleasing *)name
+                               type:(SInt32 *)fieldType
+                            fieldID:(SInt32 *)fieldID
+                              error:(NSError *__autoreleasing *)error
 {
-  if (name != NULL) {
+  if (name != nil) {
     *name = nil;
   }
-  int ft = [self readByte];
+
+  UInt8 ft;
+  if (![self readByte:&ft error:error]) {
+    return NO;
+  }
   if (fieldType != NULL) {
     *fieldType = ft;
   }
-  if (ft != TType_STOP) {
-    int fid = [self readI16];
+  if (ft != TTypeSTOP) {
+    SInt16 fid;
+    if (![self readI16:&fid error:error]) {
+      return NO;
+    }
     if (fieldID != NULL) {
       *fieldID = fid;
     }
   }
+  return YES;
 }
 
 
-- (void) readFieldEnd {}
+-(BOOL) readFieldEnd:(NSError *__autoreleasing *)error
+{
+  return YES;
+}
 
 
-- (int32_t) readI32
+-(BOOL) readString:(NSString *__autoreleasing *)value error:(NSError *__autoreleasing *)error
 {
-  uint8_t i32rd[4];
-  [mTransport readAll: i32rd offset: 0 length: 4];
-  return
-    ((i32rd[0] & 0xff) << 24) |
-    ((i32rd[1] & 0xff) << 16) |
-    ((i32rd[2] & 0xff) <<  8) |
-    ((i32rd[3] & 0xff));
+  SInt32 size;
+  if (![self readI32:&size error:error]) {
+    return NO;
+  }
+
+  NSString *string = [self readStringBody:size error:error];
+  if (!string) {
+    return NO;
+  }
+
+  *value = string;
+
+  return YES;
 }
 
 
-- (NSString *) readString
+-(BOOL) readBool:(BOOL *)value error:(NSError *__autoreleasing *)error
 {
-  int32_t size = [self readI32];
-  return [self readStringBody: size];
+  UInt8 byte;
+  if (![self readByte:&byte error:error]) {
+    return NO;
+  }
+
+  *value = byte == 1;
+
+  return YES;
 }
 
 
-- (BOOL) readBool
+-(BOOL) readByte:(UInt8 *)value error:(NSError *__autoreleasing *)error
 {
-  return [self readByte] == 1;
+  UInt8 buff[1];
+  if (![_transport readAll:buff offset:0 length:1 error:error]) {
+    PROTOCOL_TRANSPORT_ERROR(NO, error, @"Transport read failed");
+  }
+
+  *value = buff[0];
+
+  return YES;
 }
 
-- (uint8_t) readByte
+
+-(BOOL) readI16:(SInt16 *)value error:(NSError *__autoreleasing *)error
 {
-  uint8_t myByte;
-  [mTransport readAll: &myByte offset: 0 length: 1];
-  return myByte;
+  UInt8 buff[2];
+  if (![_transport readAll:buff offset:0 length:2 error:error]) {
+    PROTOCOL_TRANSPORT_ERROR(NO, error, @"Transport read failed");
+  }
+
+  *value =
+    ((SInt16)(buff[0] & 0xff) << 8) |
+    ((SInt16)(buff[1] & 0xff));
+
+  return YES;
 }
 
-- (short) readI16
+
+-(BOOL) readI32:(SInt32 *)value error:(NSError *__autoreleasing *)error
 {
-  uint8_t buff[2];
-  [mTransport readAll: buff offset: 0 length: 2];
-  return (short)
-    (((buff[0] & 0xff) << 8) |
-     ((buff[1] & 0xff)));
+  UInt8 i32rd[4];
+  if (![_transport readAll:i32rd offset:0 length:4 error:error]) {
+    PROTOCOL_TRANSPORT_ERROR(NO, error, @"Transport read failed");
+  }
+
+  *value =
+    ((i32rd[0] & 0xff) << 24) |
+    ((i32rd[1] & 0xff) << 16) |
+    ((i32rd[2] & 0xff) <<  8) |
+    ((i32rd[3] & 0xff));
+
+  return YES;
 }
 
-- (int64_t) readI64
+
+-(BOOL) readI64:(SInt64 *)value error:(NSError *__autoreleasing *)error
 {
-  uint8_t i64rd[8];
-  [mTransport readAll: i64rd offset: 0 length: 8];
-  return
-    ((int64_t)(i64rd[0] & 0xff) << 56) |
-    ((int64_t)(i64rd[1] & 0xff) << 48) |
-    ((int64_t)(i64rd[2] & 0xff) << 40) |
-    ((int64_t)(i64rd[3] & 0xff) << 32) |
-    ((int64_t)(i64rd[4] & 0xff) << 24) |
-    ((int64_t)(i64rd[5] & 0xff) << 16) |
-    ((int64_t)(i64rd[6] & 0xff) <<  8) |
-    ((int64_t)(i64rd[7] & 0xff));
+  UInt8 buff[8];
+  if (![_transport readAll:buff offset:0 length:8 error:error]) {
+    PROTOCOL_TRANSPORT_ERROR(NO, error, @"Transport read failed");
+  }
+
+  *value =
+    ((SInt64)(buff[0] & 0xff) << 56) |
+    ((SInt64)(buff[1] & 0xff) << 48) |
+    ((SInt64)(buff[2] & 0xff) << 40) |
+    ((SInt64)(buff[3] & 0xff) << 32) |
+    ((SInt64)(buff[4] & 0xff) << 24) |
+    ((SInt64)(buff[5] & 0xff) << 16) |
+    ((SInt64)(buff[6] & 0xff) <<  8) |
+    ((SInt64)(buff[7] & 0xff));
+
+  return YES;
 }
 
-- (double) readDouble
+
+-(BOOL) readDouble:(double *)value error:(NSError *__autoreleasing *)error
 {
   // FIXME - will this get us into trouble on PowerPC?
-  int64_t ieee754 = [self readI64];
-  return *((double *) &ieee754);
+  return [self readI64:(SInt64 *)value error:error];
 }
 
 
-- (NSData *) readBinary
+-(BOOL) readBinary:(NSData *__autoreleasing *)value error:(NSError *__autoreleasing *)error
 {
-  int32_t size = [self readI32];
-  size_t binarySize = CheckedCastInt32ToSizeT(size);
-  uint8_t * buff = malloc(binarySize);
-  if (buff == NULL) {
-    @throw [TProtocolException
-             exceptionWithName: @"TProtocolException"
-             reason: [NSString stringWithFormat: @"Out of memory.  Unable to allocate %d bytes trying to read binary data.",
-                               size]];
+  SInt32 size;
+  if (![self readI32:&size error:error]) {
+    return NO;
+  }
+
+  NSMutableData *data = [NSMutableData dataWithLength:size];
+  if (!data) {
+    PROTOCOL_ERROR(NO, Unknown, @"Unable to allocate %d bytes", (int)size);
   }
-  [mTransport readAll: buff offset: 0 length: binarySize];
-  return [NSData dataWithBytesNoCopy: buff length: binarySize];
+
+  if (![_transport readAll:data.mutableBytes offset:0 length:size error:error]) {
+    PROTOCOL_TRANSPORT_ERROR(NO, error, @"Transport read failed");
+  }
+
+  *value = data;
+
+  return YES;
 }
 
 
-- (void) readMapBeginReturningKeyType: (int *) keyType
-                            valueType: (int *) valueType
-                                 size: (int *) size
+-(BOOL) readMapBeginReturningKeyType:(SInt32 *)keyType
+                           valueType:(SInt32 *)valueType
+                                size:(SInt32 *)size
+                               error:(NSError *__autoreleasing *)error
 {
-  int kt = [self readByte];
-  int vt = [self readByte];
-  int s = [self readI32];
+  UInt8 kt;
+  if (![self readByte:&kt error:error]) {
+    return NO;
+  }
+
+  UInt8 vt;
+  if (![self readByte:&vt error:error]) {
+    return NO;
+  }
+
+  SInt32 s;
+  if (![self readI32:&s error:error]) {
+    return NO;
+  }
+
   if (keyType != NULL) {
     *keyType = kt;
   }
+
   if (valueType != NULL) {
     *valueType = vt;
   }
+
   if (size != NULL) {
     *size = s;
   }
+
+  return YES;
 }
 
-- (void) readMapEnd {}
 
+-(BOOL) readMapEnd:(NSError *__autoreleasing *)error
+{
+  return YES;
+}
 
-- (void) readSetBeginReturningElementType: (int *) elementType
-                                     size: (int *) size
+
+-(BOOL) readSetBeginReturningElementType:(SInt32 *)elementType
+                                    size:(SInt32 *)size
+                                   error:(NSError *__autoreleasing *)error
 {
-  int et = [self readByte];
-  int s = [self readI32];
+  UInt8 et;
+  if (![self readByte:&et error:error]) {
+    return NO;
+  }
+
+  SInt32 s;
+  if (![self readI32:&s error:error]) {
+    return NO;
+  }
+
   if (elementType != NULL) {
     *elementType = et;
   }
+
   if (size != NULL) {
     *size = s;
   }
+
+  return YES;
 }
 
 
-- (void) readSetEnd {}
+-(BOOL) readSetEnd:(NSError *__autoreleasing *)error
+{
+  return YES;
+}
 
 
-- (void) readListBeginReturningElementType: (int *) elementType
-                                      size: (int *) size
+-(BOOL) readListBeginReturningElementType:(SInt32 *)elementType
+                                     size:(SInt32 *)size
+                                    error:(NSError *__autoreleasing *)error
 {
-  int et = [self readByte];
-  int s = [self readI32];
+  UInt8 et;
+  if (![self readByte:&et error:error]) {
+    return NO;
+  }
+
+  SInt32 s;
+  if (![self readI32:&s error:error]) {
+    return NO;
+  }
+
   if (elementType != NULL) {
     *elementType = et;
   }
+
   if (size != NULL) {
     *size = s;
   }
+
+  return YES;
+}
+
+
+-(BOOL) readListEnd:(NSError *__autoreleasing *)error
+{
+  return YES;
 }
 
 
-- (void) readListEnd {}
+
+-(BOOL) writeMessageBeginWithName:(NSString *)name
+                             type:(SInt32)messageType
+                       sequenceID:(SInt32)sequenceID
+                            error:(NSError *__autoreleasing *)error
+{
+  if (_strictWrite) {
+
+    int version = VERSION_1 | messageType;
+
+    if (![self writeI32:version error:error]) {
+      return NO;
+    }
+
+    if (![self writeString:name error:error]) {
+      return NO;
+    }
+
+    if (![self writeI32:sequenceID error:error]) {
+      return NO;
+    }
+  }
+  else {
+
+    if (![self writeString:name error:error]) {
+      return NO;
+    }
+
+    if (![self writeByte:messageType error:error]) {
+      return NO;
+    }
+
+    if (![self writeI32:sequenceID error:error]) {
+      return NO;
+    }
+  }
+
+  _currentMessageName = name;
+
+  return YES;
+}
 
 
-- (void) writeByte: (uint8_t) value
+-(BOOL) writeMessageEnd:(NSError *__autoreleasing *)error
 {
-  [mTransport write: &value offset: 0 length: 1];
+  _currentMessageName = nil;
+  return YES;
 }
 
 
-- (void) writeMessageBeginWithName: (NSString *) name
-                              type: (int) messageType
-                        sequenceID: (int) sequenceID
+-(BOOL) writeStructBeginWithName:(NSString *)name
+                           error:(NSError *__autoreleasing *)error
 {
-  if (mStrictWrite) {
-    int version = (VERSION_1 << 16) | messageType;
-    [self writeI32: version];
-    [self writeString: name];
-    [self writeI32: sequenceID];
-  } else {
-    [self writeString: name];
-    [self writeByte: CheckedCastIntToUInt8(messageType)];
-    [self writeI32: sequenceID];
-  }
+  return YES;
 }
 
 
-- (void) writeMessageEnd {}
+-(BOOL) writeStructEnd:(NSError *__autoreleasing *)error
+{
+  return YES;
+}
 
 
-- (void) writeStructBeginWithName: (NSString *) name {}
+-(BOOL) writeFieldBeginWithName:(NSString *)name
+                           type:(SInt32)fieldType
+                        fieldID:(SInt32)fieldID
+                          error:(NSError *__autoreleasing *)error
+{
+  if (![self writeByte:fieldType error:error]) {
+    return NO;
+  }
 
+  if (![self writeI16:fieldID error:error]) {
+    return NO;
+  }
 
-- (void) writeStructEnd {}
+  return YES;
+}
 
 
-- (void) writeFieldBeginWithName: (NSString *) name
-                            type: (int) fieldType
-                         fieldID: (int) fieldID
+-(BOOL) writeBool:(BOOL)value error:(NSError *__autoreleasing *)error
 {
-  [self writeByte: CheckedCastIntToUInt8(fieldType)];
-  [self writeI16: CheckedCastIntToUInt8(fieldID)];
+  return [self writeByte:(value ? 1 : 0) error:error];
 }
 
 
-- (void) writeI32: (int32_t) value
+-(BOOL) writeByte:(UInt8)value error:(NSError *__autoreleasing *)error
 {
-  uint8_t buff[4];
-  buff[0] = 0xFF & (value >> 24);
-  buff[1] = 0xFF & (value >> 16);
-  buff[2] = 0xFF & (value >> 8);
-  buff[3] = 0xFF & value;
-  [mTransport write: buff offset: 0 length: 4];
+  if (![_transport write:&value offset:0 length:1 error:error]) {
+    PROTOCOL_TRANSPORT_ERROR(NO, error, @"Transport write failed");
+  }
+  return YES;
 }
 
-- (void) writeI16: (short) value
+
+-(BOOL) writeI16:(short)value error:(NSError *__autoreleasing *)error
 {
-  uint8_t buff[2];
+  UInt8 buff[2];
   buff[0] = 0xff & (value >> 8);
   buff[1] = 0xff & value;
-  [mTransport write: buff offset: 0 length: 2];
+
+  if (![_transport write:buff offset:0 length:2 error:error]) {
+    PROTOCOL_TRANSPORT_ERROR(NO, error, @"Transport write failed");
+  }
+
+  return YES;
+}
+
+
+-(BOOL) writeI32:(SInt32)value error:(NSError *__autoreleasing *)error
+{
+  UInt8 buff[4];
+  buff[0] = 0xFF & (value >> 24);
+  buff[1] = 0xFF & (value >> 16);
+  buff[2] = 0xFF & (value >> 8);
+  buff[3] = 0xFF & value;
+
+  if (![_transport write:buff offset:0 length:4 error:error]) {
+    PROTOCOL_TRANSPORT_ERROR(NO, error, @"Transport write failed");
+  }
+
+  return YES;
 }
 
 
-- (void) writeI64: (int64_t) value
+-(BOOL) writeI64:(SInt64)value error:(NSError *__autoreleasing *)error
 {
-  uint8_t buff[8];
+  UInt8 buff[8];
   buff[0] = 0xFF & (value >> 56);
   buff[1] = 0xFF & (value >> 48);
   buff[2] = 0xFF & (value >> 40);
@@ -447,84 +594,147 @@ static TBinaryProtocolFactory * gSharedFactory = nil;
   buff[5] = 0xFF & (value >> 16);
   buff[6] = 0xFF & (value >> 8);
   buff[7] = 0xFF & value;
-  [mTransport write: buff offset: 0 length: 8];
+
+  if (![_transport write:buff offset:0 length:8 error:error]) {
+    PROTOCOL_TRANSPORT_ERROR(NO, error, @"Transport write failed");
+  }
+
+  return YES;
 }
 
-- (void) writeDouble: (double) value
+
+-(BOOL) writeDouble:(double)value error:(NSError *__autoreleasing *)error
 {
-  // spit out IEEE 754 bits - FIXME - will this get us in trouble on
-  // PowerPC?
-  [self writeI64: *((int64_t *) &value)];
+  // FIXME - will this get us in trouble on PowerPC?
+  if (![self writeI64:*(SInt64 *)&value error:error]) {
+    return NO;
+  }
+
+  return YES;
 }
 
 
-- (void) writeString: (NSString *) value
+-(BOOL) writeString:(NSString *)value error:(NSError *__autoreleasing *)error
 {
   if (value != nil) {
-    const char * utf8Bytes = [value UTF8String];
-    size_t length = strlen(utf8Bytes);
-    int32_t size = CheckedCastSizeTToInt32(length);
-    [self writeI32: size];
-    [mTransport write: (uint8_t *) utf8Bytes offset: 0 length: length];
-  } else {
+
+    const char *utf8Bytes = [value UTF8String];
+
+    SInt32 length = (SInt32)strlen(utf8Bytes);
+    if (![self writeI32:length error:error]) {
+      return NO;
+    }
+
+    if (![_transport write:(UInt8 *)utf8Bytes offset:0 length:(int)length error:error]) {
+      PROTOCOL_TRANSPORT_ERROR(NO, error, @"Transport write failed");
+    }
+
+  }
+  else {
+
     // instead of crashing when we get null, let's write out a zero
     // length string
-    [self writeI32: 0];
+    if (![self writeI32:0 error:error]) {
+      return NO;
+    }
+
   }
+
+  return YES;
 }
 
 
-- (void) writeBinary: (NSData *) data
+-(BOOL) writeBinary:(NSData *)data error:(NSError *__autoreleasing *)error
 {
-  int32_t size = CheckedCastSizeTToInt32([data length]);
-  [self writeI32: size];
-  [mTransport write: [data bytes] offset: 0 length: [data length]];
+  if (![self writeI32:(SInt32)data.length error:error]) {
+    return NO;
+  }
+
+  if (![_transport write:data.bytes offset:0 length:(UInt32)data.length error:error]) {
+    PROTOCOL_TRANSPORT_ERROR(NO, error, @"Transport write failed");
+  }
+
+  return YES;
 }
 
-- (void) writeFieldStop
+
+-(BOOL) writeFieldStop:(NSError *__autoreleasing *)error
 {
-  [self writeByte: TType_STOP];
+  if (![self writeByte:TTypeSTOP error:error]) {
+    return NO;
+  }
+
+  return YES;
 }
 
 
-- (void) writeFieldEnd {}
+-(BOOL) writeFieldEnd:(NSError *__autoreleasing *)error
+{
+  return YES;
+}
 
 
-- (void) writeMapBeginWithKeyType: (int) keyType
-                        valueType: (int) valueType
-                             size: (int) size
+-(BOOL) writeMapBeginWithKeyType:(SInt32)keyType
+                       valueType:(SInt32)valueType
+                            size:(SInt32)size
+                           error:(NSError *__autoreleasing *)error
 {
-  [self writeByte: CheckedCastIntToUInt8(keyType)];
-  [self writeByte: CheckedCastIntToUInt8(valueType)];
-  [self writeI32: size];
+  if (![self writeByte:keyType error:error]) {
+    return NO;
+  }
+  if (![self writeByte:valueType error:error]) {
+    return NO;
+  }
+  if (![self writeI32:(int)size error:error]) {
+    return NO;
+  }
+  return YES;
 }
 
-- (void) writeMapEnd {}
 
-
-- (void) writeSetBeginWithElementType: (int) elementType
-                                 size: (int) size
+-(BOOL) writeMapEnd:(NSError *__autoreleasing *)error
 {
-  [self writeByte: CheckedCastIntToUInt8(elementType)];
-  [self writeI32: size];
+  return YES;
 }
 
-- (void) writeSetEnd {}
 
+-(BOOL) writeSetBeginWithElementType:(SInt32)elementType
+                                size:(SInt32)size
+                               error:(NSError *__autoreleasing *)error
+{
+  if (![self writeByte:elementType error:error]) {
+    return NO;
+  }
+  if (![self writeI32:size error:error]) {
+    return NO;
+  }
+  return YES;
+}
 
-- (void) writeListBeginWithElementType: (int) elementType
-                                  size: (int) size
+
+-(BOOL) writeSetEnd:(NSError *__autoreleasing *)error
 {
-  [self writeByte: CheckedCastIntToUInt8(elementType)];
-  [self writeI32: size];
+  return YES;
 }
 
-- (void) writeListEnd {}
+
+-(BOOL) writeListBeginWithElementType:(SInt32)elementType
+                                 size:(SInt32)size
+                                error:(NSError *__autoreleasing *)error
+{
+  if (![self writeByte:elementType error:error]) {
+    return NO;
+  }
+  if (![self writeI32:size error:error]) {
+    return NO;
+  }
+  return YES;
+}
 
 
-- (void) writeBool: (BOOL) value
+-(BOOL) writeListEnd:(NSError *__autoreleasing *)error
 {
-  [self writeByte: (value ? 1 : 0)];
+  return YES;
 }
 
 @end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/protocol/TCompactProtocol.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/protocol/TCompactProtocol.h b/lib/cocoa/src/protocol/TCompactProtocol.h
index 3c9195c..3f6accc 100644
--- a/lib/cocoa/src/protocol/TCompactProtocol.h
+++ b/lib/cocoa/src/protocol/TCompactProtocol.h
@@ -21,16 +21,22 @@
 #import "TTransport.h"
 #import "TProtocolFactory.h"
 
+NS_ASSUME_NONNULL_BEGIN
+
+
 @interface TCompactProtocol : NSObject <TProtocol>
 
-- (id) initWithTransport: (id <TTransport>) transport;
+-(id) initWithTransport:(id <TTransport>)transport;
 
 @end
 
 @interface TCompactProtocolFactory : NSObject <TProtocolFactory>
 
-+ (TCompactProtocolFactory *) sharedFactory;
++(TCompactProtocolFactory *) sharedFactory;
 
-- (TCompactProtocol *) newProtocolOnTransport: (id <TTransport>) transport;
+-(TCompactProtocol *) newProtocolOnTransport:(id <TTransport>)transport;
 
 @end
+
+
+NS_ASSUME_NONNULL_END
\ No newline at end of file


[7/7] thrift git commit: THRIFT-2905 Cocoa compiler should have option to produce "modern" Objective-C Client: Cocoa (ObjectiveC & Swift) Author: Kevin Wooten

Posted by je...@apache.org.
THRIFT-2905 Cocoa compiler should have option to produce "modern" Objective-C
Client: Cocoa (ObjectiveC & Swift)
Author: Kevin Wooten <ke...@wooten.com>

This closes #539


Project: http://git-wip-us.apache.org/repos/asf/thrift/repo
Commit: http://git-wip-us.apache.org/repos/asf/thrift/commit/56e5b9b0
Tree: http://git-wip-us.apache.org/repos/asf/thrift/tree/56e5b9b0
Diff: http://git-wip-us.apache.org/repos/asf/thrift/diff/56e5b9b0

Branch: refs/heads/master
Commit: 56e5b9b01b5a033306d583cd2aec07a0dda3c9f5
Parents: 983bf7d
Author: Jens Geyer <je...@apache.org>
Authored: Fri Oct 9 22:01:55 2015 +0200
Committer: Jens Geyer <je...@apache.org>
Committed: Fri Oct 9 22:01:55 2015 +0200

----------------------------------------------------------------------
 Thrift.podspec                                  |   18 +
 compiler/cpp/CMakeLists.txt                     |    1 +
 compiler/cpp/Makefile.am                        |    1 +
 compiler/cpp/compiler.vcxproj                   |    1 +
 compiler/cpp/compiler.vcxproj.filters           |    3 +
 compiler/cpp/src/generate/t_cocoa_generator.cc  | 1666 ++++++++------
 compiler/cpp/src/generate/t_swift_generator.cc  | 2145 ++++++++++++++++++
 lib/cocoa/src/TApplicationError.h               |   55 +
 lib/cocoa/src/TApplicationError.m               |  231 ++
 lib/cocoa/src/TApplicationException.h           |   49 -
 lib/cocoa/src/TApplicationException.m           |  146 --
 lib/cocoa/src/TBaseClient.h                     |    9 +-
 lib/cocoa/src/TBaseClient.m                     |   41 +-
 lib/cocoa/src/TBinary.swift                     |  122 +
 lib/cocoa/src/TEnum.swift                       |   31 +
 lib/cocoa/src/TError.h                          |   23 +
 lib/cocoa/src/TError.m                          |   23 +
 lib/cocoa/src/TException.h                      |   34 -
 lib/cocoa/src/TException.m                      |   65 -
 lib/cocoa/src/TList.swift                       |  148 ++
 lib/cocoa/src/TMap.swift                        |  158 ++
 lib/cocoa/src/TObjective-C.h                    |   72 -
 lib/cocoa/src/TProcessor.h                      |   10 +-
 lib/cocoa/src/TProcessorFactory.h               |    8 +-
 lib/cocoa/src/TProtocol.swift                   |  190 ++
 lib/cocoa/src/TSerializable.swift               |  178 ++
 lib/cocoa/src/TSet.swift                        |  161 ++
 lib/cocoa/src/TSharedProcessorFactory.h         |    9 +-
 lib/cocoa/src/TSharedProcessorFactory.m         |   29 +-
 lib/cocoa/src/TStruct.swift                     |   31 +
 lib/cocoa/src/protocol/TBase.h                  |   13 +-
 lib/cocoa/src/protocol/TBinaryProtocol.h        |   32 +-
 lib/cocoa/src/protocol/TBinaryProtocol.m        |  766 ++++---
 lib/cocoa/src/protocol/TCompactProtocol.h       |   12 +-
 lib/cocoa/src/protocol/TCompactProtocol.m       | 1038 ++++++---
 lib/cocoa/src/protocol/TMultiplexedProtocol.h   |   17 +-
 lib/cocoa/src/protocol/TMultiplexedProtocol.m   |   65 +-
 lib/cocoa/src/protocol/TProtocol.h              |  170 +-
 lib/cocoa/src/protocol/TProtocolDecorator.h     |   12 +-
 lib/cocoa/src/protocol/TProtocolDecorator.m     |  273 ++-
 lib/cocoa/src/protocol/TProtocolError.h         |   76 +
 lib/cocoa/src/protocol/TProtocolError.m         |   33 +
 lib/cocoa/src/protocol/TProtocolException.h     |   25 -
 lib/cocoa/src/protocol/TProtocolException.m     |   23 -
 lib/cocoa/src/protocol/TProtocolFactory.h       |    9 +-
 lib/cocoa/src/protocol/TProtocolUtil.h          |   12 +-
 lib/cocoa/src/protocol/TProtocolUtil.m          |  197 +-
 lib/cocoa/src/server/TSocketServer.h            |   24 +-
 lib/cocoa/src/server/TSocketServer.m            |  193 +-
 lib/cocoa/src/transport/TAsyncTransport.h       |   23 +-
 lib/cocoa/src/transport/TFramedTransport.h      |   12 +-
 lib/cocoa/src/transport/TFramedTransport.m      |  219 +-
 lib/cocoa/src/transport/THTTPClient.h           |   42 -
 lib/cocoa/src/transport/THTTPClient.m           |  161 --
 lib/cocoa/src/transport/THTTPSessionTransport.h |   47 +
 lib/cocoa/src/transport/THTTPSessionTransport.m |  268 +++
 lib/cocoa/src/transport/THTTPTransport.h        |   39 +
 lib/cocoa/src/transport/THTTPTransport.m        |  182 ++
 lib/cocoa/src/transport/TMemoryBuffer.h         |   20 +-
 lib/cocoa/src/transport/TMemoryBuffer.m         |  115 +-
 .../src/transport/TNSFileHandleTransport.h      |   17 +-
 .../src/transport/TNSFileHandleTransport.m      |   99 +-
 lib/cocoa/src/transport/TNSStreamTransport.h    |   21 +-
 lib/cocoa/src/transport/TNSStreamTransport.m    |  141 +-
 lib/cocoa/src/transport/TSSLSocketClient.h      |   40 -
 lib/cocoa/src/transport/TSSLSocketClient.m      |  261 ---
 lib/cocoa/src/transport/TSSLSocketException.h   |   29 -
 lib/cocoa/src/transport/TSSLSocketException.m   |   42 -
 lib/cocoa/src/transport/TSSLSocketTransport.h   |   37 +
 lib/cocoa/src/transport/TSSLSocketTransport.m   |  304 +++
 .../src/transport/TSSLSocketTransportError.h    |   30 +
 .../src/transport/TSSLSocketTransportError.m    |   23 +
 lib/cocoa/src/transport/TSocketClient.h         |   36 -
 lib/cocoa/src/transport/TSocketClient.m         |   87 -
 lib/cocoa/src/transport/TSocketTransport.h      |   34 +
 lib/cocoa/src/transport/TSocketTransport.m      |   73 +
 lib/cocoa/src/transport/TTransport.h            |   36 +-
 lib/cocoa/src/transport/TTransportError.h       |   43 +
 lib/cocoa/src/transport/TTransportError.m       |   27 +
 lib/cocoa/src/transport/TTransportException.h   |   30 -
 lib/cocoa/src/transport/TTransportException.m   |   44 -
 81 files changed, 7993 insertions(+), 3237 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/Thrift.podspec
----------------------------------------------------------------------
diff --git a/Thrift.podspec b/Thrift.podspec
new file mode 100644
index 0000000..39d3780
--- /dev/null
+++ b/Thrift.podspec
@@ -0,0 +1,18 @@
+Pod::Spec.new do |s|
+  s.name          = "Thrift"
+  s.version       = "1.0.0"
+  s.summary       = "Apache Thrift is a lightweight, language-independent software stack with an associated code generation mechanism for RPC."
+  s.description   = <<-DESC
+The Apache Thrift software framework, for scalable cross-language services development, combines a software stack with a code generation engine to build services that work efficiently and seamlessly between C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, OCaml and Delphi and other languages.
+                    DESC
+  s.homepage      = "http://thrift.apache.org"
+  s.license       = { :type => 'Apache License, Version 2.0', :url => 'https://raw.github.com/apache/thrift/thrift-0.9.0/LICENSE' }
+  s.author        = { "The Apache Software Foundation" => "apache@apache.org" }
+  s.requires_arc  = true
+  s.ios.deployment_target = '7.0'
+  s.osx.deployment_target = '10.8'
+  s.ios.framework = 'CFNetwork'
+  s.osx.framework = 'CoreServices'
+  s.source        = { :git => "https://github.com/apache/thrift.git", :tag => "thrift-1.0.0" }
+  s.source_files  = 'lib/cocoa/src/**/*.{h,m,swift}'
+end
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/compiler/cpp/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/compiler/cpp/CMakeLists.txt b/compiler/cpp/CMakeLists.txt
index 2d0c3f0..94b3c19 100644
--- a/compiler/cpp/CMakeLists.txt
+++ b/compiler/cpp/CMakeLists.txt
@@ -109,6 +109,7 @@ THRIFT_ADD_COMPILER(perl    "Enable compiler for Perl" ON)
 THRIFT_ADD_COMPILER(php     "Enable compiler for PHP" ON)
 THRIFT_ADD_COMPILER(erl     "Enable compiler for Erlang" ON)
 THRIFT_ADD_COMPILER(cocoa   "Enable compiler for Cocoa Objective-C" ON)
+THRIFT_ADD_COMPILER(swift   "Enable compiler for Cocoa Swift" ON)
 THRIFT_ADD_COMPILER(st      "Enable compiler for Smalltalk" ON)
 THRIFT_ADD_COMPILER(ocaml   "Enable compiler for OCaml" ON)
 THRIFT_ADD_COMPILER(hs      "Enable compiler for Haskell" ON)

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/compiler/cpp/Makefile.am
----------------------------------------------------------------------
diff --git a/compiler/cpp/Makefile.am b/compiler/cpp/Makefile.am
index 2aa6913..427062c 100644
--- a/compiler/cpp/Makefile.am
+++ b/compiler/cpp/Makefile.am
@@ -83,6 +83,7 @@ thrift_SOURCES += src/generate/t_c_glib_generator.cc \
                   src/generate/t_php_generator.cc \
                   src/generate/t_erl_generator.cc \
                   src/generate/t_cocoa_generator.cc \
+                  src/generate/t_swift_generator.cc \
                   src/generate/t_st_generator.cc \
                   src/generate/t_ocaml_generator.cc \
                   src/generate/t_hs_generator.cc \

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/compiler/cpp/compiler.vcxproj
----------------------------------------------------------------------
diff --git a/compiler/cpp/compiler.vcxproj b/compiler/cpp/compiler.vcxproj
index bc1215f..fbd41ad 100644
--- a/compiler/cpp/compiler.vcxproj
+++ b/compiler/cpp/compiler.vcxproj
@@ -78,6 +78,7 @@
     <ClCompile Include="src\generate\t_py_generator.cc" />
     <ClCompile Include="src\generate\t_rb_generator.cc" />
     <ClCompile Include="src\generate\t_st_generator.cc" />
+	<ClCompile Include="src\generate\t_swift_generator.cc" />
     <ClCompile Include="src\generate\t_xsd_generator.cc" />
     <ClCompile Include="src\main.cc" />
     <ClCompile Include="src\md5.c" />

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/compiler/cpp/compiler.vcxproj.filters
----------------------------------------------------------------------
diff --git a/compiler/cpp/compiler.vcxproj.filters b/compiler/cpp/compiler.vcxproj.filters
index 5126019..6e41afb 100644
--- a/compiler/cpp/compiler.vcxproj.filters
+++ b/compiler/cpp/compiler.vcxproj.filters
@@ -165,6 +165,9 @@
     <ClCompile Include="src\generate\t_st_generator.cc">
       <Filter>generate</Filter>
     </ClCompile>
+    <ClCompile Include="src\generate\t_swift_generator.cc">
+      <Filter>generate</Filter>
+    </ClCompile>
     <ClCompile Include="src\generate\t_xsd_generator.cc">
       <Filter>generate</Filter>
     </ClCompile>


[5/7] thrift git commit: THRIFT-2905 Cocoa compiler should have option to produce "modern" Objective-C Client: Cocoa (ObjectiveC & Swift) Author: Kevin Wooten

Posted by je...@apache.org.
http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/compiler/cpp/src/generate/t_swift_generator.cc
----------------------------------------------------------------------
diff --git a/compiler/cpp/src/generate/t_swift_generator.cc b/compiler/cpp/src/generate/t_swift_generator.cc
new file mode 100644
index 0000000..80f1c07
--- /dev/null
+++ b/compiler/cpp/src/generate/t_swift_generator.cc
@@ -0,0 +1,2145 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <string>
+#include <fstream>
+#include <iostream>
+#include <vector>
+
+#include <stdlib.h>
+#include <sys/stat.h>
+#include <sstream>
+#include "t_oop_generator.h"
+#include "platform.h"
+
+using std::map;
+using std::ostream;
+using std::ofstream;
+using std::ostringstream;
+using std::string;
+using std::stringstream;
+using std::vector;
+
+static const string endl = "\n"; // avoid ostream << std::endl flushes
+
+/**
+ * Swift code generator.
+ *
+ * Designed from the Objective-C (aka Cocoa) generator.
+ */
+class t_swift_generator : public t_oop_generator {
+public:
+  t_swift_generator(t_program* program,
+                    const map<string, string>& parsed_options,
+                    const string& option_string)
+    : t_oop_generator(program) {
+    (void)option_string;
+    map<string, string>::const_iterator iter;
+
+    iter = parsed_options.find("log_unexpected");
+    log_unexpected_ = (iter != parsed_options.end());
+
+    iter = parsed_options.find("async_clients");
+    async_clients_ = (iter != parsed_options.end());
+      
+    iter = parsed_options.find("promise_kit");
+    promise_kit_ = (iter != parsed_options.end());
+      
+    iter = parsed_options.find("debug_descriptions");
+    debug_descriptions_ = (iter != parsed_options.end());
+    
+    out_dir_base_ = "gen-swift";
+  }
+
+  /**
+   * Init and close methods
+   */
+
+  void init_generator();
+  void close_generator();
+
+  void generate_consts(vector<t_const*> consts);
+
+  /**
+   * Program-level generation functions
+   */
+
+  void generate_typedef(t_typedef* ttypedef);
+  void generate_enum(t_enum* tenum);
+  void generate_struct(t_struct* tstruct);
+  void generate_xception(t_struct* txception);
+  void generate_service(t_service* tservice);
+
+  void print_const_value(ostream& out,
+                         string name,
+                         t_type* type,
+                         t_const_value* value,
+                         bool defval = false,
+                         bool is_property = false);
+  void render_const_value(ostream& out,
+                          t_type* type,
+                          t_const_value* value);
+
+  void generate_swift_struct(ofstream& out,
+                             t_struct* tstruct,
+                             bool is_private);
+  void generate_swift_struct_init(ofstream& out,
+                                  t_struct* tstruct,
+                                  bool all,
+                                  bool is_private);
+  
+  void generate_swift_struct_implementation(ofstream& out,
+                                            t_struct* tstruct,
+                                            bool is_result,
+                                            bool is_private);
+  void generate_swift_struct_hashable_extension(ofstream& out,
+                                                t_struct* tstruct,
+                                                bool is_private);
+  void generate_swift_struct_equatable_extension(ofstream& out,
+                                                 t_struct* tstruct,
+                                                 bool is_private);
+  void generate_swift_struct_thrift_extension(ofstream& out,
+                                              t_struct* tstruct,
+                                              bool is_result,
+                                              bool is_private);
+  void generate_swift_struct_reader(ofstream& out, t_struct* tstruct, bool is_private);
+  void generate_swift_struct_writer(ofstream& out,t_struct* tstruct, bool is_private);
+  void generate_swift_struct_result_writer(ofstream& out, t_struct* tstruct);
+  void generate_swift_struct_printable_extension(ofstream& out, t_struct* tstruct);
+
+  string function_result_helper_struct_type(t_service *tservice, t_function* tfunction);
+  string function_args_helper_struct_type(t_service* tservice, t_function* tfunction);
+  void generate_function_helpers(t_service *tservice, t_function* tfunction);
+
+  /**
+   * Service-level generation functions
+   */
+
+  void generate_swift_service_protocol(ofstream& out, t_service* tservice);
+  void generate_swift_service_protocol_async(ofstream& out, t_service* tservice);
+
+  void generate_swift_service_client(ofstream& out, t_service* tservice);
+  void generate_swift_service_client_async(ofstream& out, t_service* tservice);
+
+  void generate_swift_service_client_send_function_implementation(ofstream& out,
+                                                                  t_service* tservice,
+                                                                  t_function* tfunction,
+                                                                  bool needs_protocol);
+  void generate_swift_service_client_send_function_invocation(ofstream& out, t_function* tfunction);
+  void generate_swift_service_client_send_async_function_invocation(ofstream& out,
+                                                                    t_function* tfunction);
+  void generate_swift_service_client_recv_function_implementation(ofstream& out,
+                                                                  t_service* tservice,
+                                                                  t_function* tfunction,
+                                                                  bool needs_protocol);
+  void generate_swift_service_client_implementation(ofstream& out, t_service* tservice);
+  void generate_swift_service_client_async_implementation(ofstream& out, t_service* tservice);
+
+  void generate_swift_service_server(ofstream& out, t_service* tservice);
+  void generate_swift_service_server_implementation(ofstream& out, t_service* tservice);
+  void generate_swift_service_helpers(t_service* tservice);
+
+  /**
+   * Helper rendering functions
+   */
+
+  string swift_imports();
+  string swift_thrift_imports();
+  string type_name(t_type* ttype, bool is_optional=false, bool is_forced=false);
+  string base_type_name(t_base_type* tbase);
+  string declare_property(t_field* tfield, bool is_private);
+  string function_signature(t_function* tfunction);
+  string async_function_signature(t_function* tfunction);
+  string promise_function_signature(t_function* tfunction);
+  string function_name(t_function* tfunction);
+  string argument_list(t_struct* tstruct, string protocol_name, bool is_internal);
+  string type_to_enum(t_type* ttype, bool qualified=false);
+
+private:
+  
+  void block_open(ostream& out) {
+    out << " {" << endl;
+    indent_up();
+  }
+  
+  void block_close(ostream& out, bool end_line=true) {
+    indent_down();
+    indent(out) << "}";
+    if (end_line) out << endl;
+  }
+
+  
+  bool field_is_optional(t_field* tfield) {
+    return tfield->get_req() == t_field::T_OPTIONAL;
+  }
+  
+  bool struct_has_required_fields(t_struct* tstruct) {
+    const vector<t_field*>& members = tstruct->get_members();
+    vector<t_field*>::const_iterator m_iter;
+    for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
+      if (!field_is_optional(*m_iter)) {
+        return true;
+      }
+    }
+    return false;
+  }
+  
+  bool struct_has_optional_fields(t_struct* tstruct) {
+    const vector<t_field*>& members = tstruct->get_members();
+    vector<t_field*>::const_iterator m_iter;
+    for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
+      if (field_is_optional(*m_iter)) {
+        return true;
+      }
+    }
+    return false;
+  }
+  
+  string constants_declarations_;
+
+  /**
+   * File streams
+   */
+
+  ofstream f_decl_;
+  ofstream f_impl_;
+
+  bool log_unexpected_;
+  bool async_clients_;
+  bool promise_kit_;
+  bool debug_descriptions_;
+};
+
+/**
+ * Prepares for file generation by opening up the necessary file output
+ * streams.
+ */
+void t_swift_generator::init_generator() {
+  // Make output directory
+  MKDIR(get_out_dir().c_str());
+
+  // we have a .swift declarations file...
+  string f_decl_name = capitalize(program_name_) + ".swift";
+  string f_decl_fullname = get_out_dir() + f_decl_name;
+  f_decl_.open(f_decl_fullname.c_str());
+
+  f_decl_ << autogen_comment() << endl;
+
+  f_decl_ << swift_imports() << swift_thrift_imports() << endl;
+
+  // ...and a .swift implementation extensions file
+  string f_impl_name = capitalize(program_name_) + "+Exts.swift";
+  string f_impl_fullname = get_out_dir() + f_impl_name;
+  f_impl_.open(f_impl_fullname.c_str());
+
+  f_impl_ << autogen_comment() << endl;
+
+  f_impl_ << swift_imports() << swift_thrift_imports() << endl;
+
+}
+
+/**
+ * Prints standard Cocoa imports
+ *
+ * @return List of imports for Cocoa libraries
+ */
+string t_swift_generator::swift_imports() {
+
+  vector<string> includes_list;
+  includes_list.push_back("Foundation");
+  
+  ostringstream includes;
+  
+  vector<string>::const_iterator i_iter;
+  for (i_iter=includes_list.begin(); i_iter!=includes_list.end(); ++i_iter) {
+    includes << "import " << *i_iter << endl;
+  }
+  
+  includes << endl;
+  
+  return includes.str();
+}
+
+/**
+ * Prints Thrift runtime imports
+ *
+ * @return List of imports necessary for Thrift runtime
+ */
+string t_swift_generator::swift_thrift_imports() {
+
+  vector<string> includes_list;
+  includes_list.push_back("Thrift");
+  
+  if (promise_kit_) {
+    includes_list.push_back("PromiseKit");
+  }
+
+  ostringstream includes;
+
+  vector<string>::const_iterator i_iter;
+  for (i_iter=includes_list.begin(); i_iter!=includes_list.end(); ++i_iter) {
+    includes << "import " << *i_iter << endl;
+  }
+  
+  includes << endl;
+
+  return includes.str();
+}
+
+/**
+ * Finish up generation.
+ */
+void t_swift_generator::close_generator() {
+  // stick our constants declarations at the end of the header file
+  // since they refer to things we are defining.
+  f_decl_ << constants_declarations_ << endl;
+}
+
+/**
+ * Generates a typedef. This is just a simple 1-liner in Swift
+ *
+ * @param ttypedef The type definition
+ */
+void t_swift_generator::generate_typedef(t_typedef* ttypedef) {
+  f_decl_ << indent() << "public typealias " << ttypedef->get_symbolic()
+          << " = " << type_name(ttypedef->get_type()) << endl;
+  f_decl_ << endl;
+}
+
+/**
+ * Generates code for an enumerated type. In Swift, this is
+ * essentially the same as the thrift definition itself, using
+ * Swift syntax.
+ *
+ * @param tenum The enumeration
+ */
+void t_swift_generator::generate_enum(t_enum* tenum) {
+  f_decl_ << indent() << "public enum " << tenum->get_name() << " : Int32";
+  block_open(f_decl_);
+
+  vector<t_enum_value*> constants = tenum->get_constants();
+  vector<t_enum_value*>::iterator c_iter;
+
+  for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) {
+    f_decl_ << indent() << "case " << (*c_iter)->get_name()
+            << " = " << (*c_iter)->get_value() << endl;
+  }
+
+  f_decl_ << endl;
+  f_decl_ << indent() << "public init() { self.init(rawValue: " << constants.front()->get_value() << ")! }" << endl;
+  
+  block_close(f_decl_);
+  f_decl_ << endl;
+  
+  f_impl_ << indent() << "extension " << tenum->get_name() << " : TEnum";
+  block_open(f_impl_);
+
+  f_impl_ << endl;
+  
+  f_impl_ << indent() << "public static func readValueFromProtocol(proto: TProtocol) throws -> " << tenum->get_name();
+  block_open(f_impl_);
+  f_impl_ << indent() << "var raw = Int32()" << endl
+          << indent() << "try proto.readI32(&raw)" << endl
+          << indent() << "return " << tenum->get_name() << "(rawValue: raw)!" << endl;
+  block_close(f_impl_);
+  f_impl_ << endl;
+  
+  f_impl_ << indent() << "public static func writeValue(value: " << tenum->get_name() << ", toProtocol proto: TProtocol) throws";
+  block_open(f_impl_);
+  f_impl_ << indent() << "try proto.writeI32(value.rawValue)" << endl;
+  block_close(f_impl_);
+  f_impl_ << endl;
+  
+  block_close(f_impl_);
+  f_impl_ << endl;
+}
+
+/**
+ * Generates public constants for all Thrift constants.
+ * 
+ * @param consts Constants to generate
+ */
+void t_swift_generator::generate_consts(vector<t_const*> consts) {
+
+  ostringstream const_interface;
+
+  // Public constants for base types & strings
+  vector<t_const*>::iterator c_iter;
+  for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
+    t_type* type = (*c_iter)->get_type();
+    const_interface << "public let " << capitalize((*c_iter)->get_name()) << " : " << type_name(type) << " = ";
+    render_const_value(const_interface, type, (*c_iter)->get_value());
+    const_interface << endl << endl;
+  }
+  
+  // this gets spit into the header file in ::close_generator
+  constants_declarations_ = const_interface.str();
+  
+}
+
+/**
+ * Generates a struct definition for a thrift data type. This is a struct
+ * with public members. Optional types are used for optional properties to
+ * allow them to be tested for availability. Separate inits are included for
+ * required properties & all properties.
+ * 
+ * Generates extensions to provide conformance to TStruct, TSerializable,
+ * Hashable & Equatable
+ *
+ * @param tstruct The struct definition
+ */
+void t_swift_generator::generate_struct(t_struct* tstruct) {
+  generate_swift_struct(f_decl_, tstruct, false);
+  generate_swift_struct_implementation(f_impl_, tstruct, false, false);
+}
+
+/**
+ * Exceptions are structs, but they conform to ErrorType
+ *
+ * @param tstruct The struct definition
+ */
+void t_swift_generator::generate_xception(t_struct* txception) {
+  generate_swift_struct(f_decl_, txception, false);
+  generate_swift_struct_implementation(f_impl_, txception, false, false);
+}
+
+/**
+ * Generate the interface for a struct. Only properties and 
+ * init methods are included.
+ *
+ * @param tstruct The struct definition
+ * @param is_private
+ *                Is the struct public or private
+ */
+void t_swift_generator::generate_swift_struct(ofstream& out,
+                                              t_struct* tstruct,
+                                              bool is_private) {
+  
+  string visibility = is_private ? "private" : "public";
+  
+  out << indent() << visibility << " struct " << tstruct->get_name();
+
+  if (tstruct->is_xception()) {
+    out << " : ErrorType";
+  }
+  
+  block_open(out);
+
+  // properties
+  const vector<t_field*>& members = tstruct->get_members();
+  vector<t_field*>::const_iterator m_iter;
+  
+  for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
+    out << endl;
+    out << indent() << declare_property(*m_iter, is_private) << endl;
+  }
+  
+  out << endl;
+  
+  // init
+  
+  indent(out) << visibility << " init()";
+  block_open(out);
+  block_close(out);
+  
+  out << endl;
+  
+  if (struct_has_required_fields(tstruct)) {
+    generate_swift_struct_init(out, tstruct, false, is_private);
+  }
+  if (struct_has_optional_fields(tstruct)) {
+    generate_swift_struct_init(out, tstruct, true, is_private);
+  }
+
+  block_close(out);
+  
+  out << endl;
+}
+
+/**
+ * Generate struct init for properties
+ *
+ * @param tstruct The structure definition
+ * @param all     Generate init with all or just required properties
+ * @param is_private
+ *                Is the initializer public or private
+ */
+void t_swift_generator::generate_swift_struct_init(ofstream& out,
+                                                   t_struct* tstruct,
+                                                   bool all,
+                                                   bool is_private) {
+
+  string visibility = is_private ? "private" : "public";
+
+  indent(out) << visibility << " init(";
+
+  const vector<t_field*>& members = tstruct->get_members();
+  vector<t_field*>::const_iterator m_iter;
+  
+  bool first=true;
+  for (m_iter = members.begin(); m_iter != members.end();) {
+    if (all || !field_is_optional(*m_iter)) {
+      if (first) {
+        first = false;
+      }
+      else {
+        out << ", ";
+      }
+      out << (*m_iter)->get_name() << ": " << type_name((*m_iter)->get_type(), field_is_optional(*m_iter));
+    }
+    ++m_iter;
+  }
+  out << ")";
+  
+  block_open(out);
+  
+  for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
+    if (all || (*m_iter)->get_req() == t_field::T_REQUIRED || (*m_iter)->get_req() == t_field::T_OPT_IN_REQ_OUT) {
+      out << indent() << "self." << (*m_iter)->get_name() << " = " << (*m_iter)->get_name() << endl;
+    }
+  }
+  
+  block_close(out);
+ 
+  out << endl;
+}
+
+/**
+ * Generate the hashable protocol implmentation
+ *
+ * @param tstruct The structure definition
+ * @param is_private
+ *                Is the struct public or private
+ */
+void t_swift_generator::generate_swift_struct_hashable_extension(ofstream& out,
+                                                                 t_struct* tstruct,
+                                                                 bool is_private) {
+
+  string visibility = is_private ? "private" : "public";
+
+  indent(out) << "extension " << tstruct->get_name() << " : Hashable";
+  
+  block_open(out);
+  
+  out << endl;
+  
+  indent(out) << visibility << " var hashValue : Int";
+  
+  block_open(out);
+  
+  
+  const vector<t_field*>& members = tstruct->get_members();
+  vector<t_field*>::const_iterator m_iter;
+
+  if (!members.empty()) {
+    indent(out) << "let prime = 31" << endl;
+    indent(out) << "var result = 1" << endl;
+    
+    for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
+      t_field* tfield = *m_iter;
+      string accessor = field_is_optional(tfield) ? "?." : ".";
+      string defaultor = field_is_optional(tfield) ? " ?? 0" : "";
+      indent(out) << "result = prime * result + (" << tfield->get_name() << accessor <<  "hashValue" << defaultor << ")" << endl;
+    }
+    
+    indent(out) << "return result" << endl;
+  }
+  else {
+    indent(out) << "return 31" << endl;
+  }
+
+  block_close(out);
+  
+  out << endl;
+  
+  block_close(out);
+
+  out << endl;
+}
+
+/**
+ * Generate the equatable protocol implementation
+ *
+ * @param tstruct The structure definition
+ * @param is_private
+ *                Is the struct public or private
+ */
+void t_swift_generator::generate_swift_struct_equatable_extension(ofstream& out,
+                                                                  t_struct* tstruct,
+                                                                  bool is_private) {
+
+  string visibility = is_private ? "private" : "public";
+  
+  indent(out) << visibility << " func ==(lhs: " << type_name(tstruct) << ", rhs: " << type_name(tstruct) << ") -> Bool";
+  
+  block_open(out);
+  
+  indent(out) << "return";
+  
+  const vector<t_field*>& members = tstruct->get_members();
+  vector<t_field*>::const_iterator m_iter;
+
+  if (members.size()) {
+    
+    out << endl;
+  
+    indent_up();
+  
+    for (m_iter = members.begin(); m_iter != members.end();) {
+      t_field* tfield = *m_iter;
+      indent(out) << "(lhs." << tfield->get_name() << " ?== rhs." << tfield->get_name() << ")";
+      if (++m_iter != members.end()) {
+        out << " &&";
+      }
+      out << endl;
+    }
+  
+    indent_down();
+    
+  }
+  else {
+    out << " true" << endl;
+  }
+  
+  block_close(out);
+  
+  out << endl;
+}
+
+/**
+ * Generate struct implementation. Produces extensions that
+ * fulfill the requisite protocols to complete the value.
+ *
+ * @param tstruct The struct definition
+ * @param is_result
+ *                If this is a result it needs a different writer
+ * @param is_private
+ *                Is the struct public or private
+ */
+void t_swift_generator::generate_swift_struct_implementation(ofstream& out,
+                                                             t_struct* tstruct,
+                                                             bool is_result,
+                                                             bool is_private) {
+  
+  generate_swift_struct_equatable_extension(out, tstruct, is_private);
+  
+  if (!is_private && !is_result) {
+    generate_swift_struct_printable_extension(out, tstruct);
+  }
+  
+  generate_swift_struct_hashable_extension(out, tstruct, is_private);
+  generate_swift_struct_thrift_extension(out, tstruct, is_result, is_private);
+
+  out << endl << endl;
+}
+
+/**
+ * Generate the TStruct protocol implementation.
+ *
+ * @param tstruct The structure definition
+ * @param is_result
+ *                Is the struct a result value
+ * @param is_private
+ *                Is the struct public or private
+ */
+void t_swift_generator::generate_swift_struct_thrift_extension(ofstream& out,
+                                                               t_struct* tstruct,
+                                                               bool is_result,
+                                                               bool is_private) {
+  
+  indent(out) << "extension " << tstruct->get_name() << " : TStruct";
+  
+  block_open(out);
+  
+  out << endl;
+  
+  generate_swift_struct_reader(out, tstruct, is_private);
+  
+  if (is_result) {
+    generate_swift_struct_result_writer(out, tstruct);
+  }
+  else {
+    generate_swift_struct_writer(out, tstruct, is_private);
+  }
+  
+  block_close(out);
+  
+  out << endl;
+}
+
+/**
+ * Generates a function to read a struct from
+ * from a protocol. (TStruct compliance)
+ *
+ * @param tstruct The structure definition
+ * @param is_private
+ *                Is the struct public or private
+ */
+void t_swift_generator::generate_swift_struct_reader(ofstream& out,
+                                                     t_struct* tstruct,
+                                                     bool is_private) {
+  
+  string visibility = is_private ? "private" : "public";
+  
+  indent(out) << visibility << " static func readValueFromProtocol(__proto: TProtocol) throws -> "
+              << tstruct->get_name();
+  
+  block_open(out);
+  
+  out << endl;
+  
+  indent(out) << "try __proto.readStructBegin()" << endl << endl;
+
+  const vector<t_field*>& fields = tstruct->get_members();
+  vector<t_field*>::const_iterator f_iter;
+  
+  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
+    bool optional = field_is_optional(*f_iter);
+    indent(out) << "var " << (*f_iter)->get_name() << " : "
+                << type_name((*f_iter)->get_type(), optional, !optional) << endl;
+  }
+  
+  out << endl;
+  
+  // Loop over reading in fields
+  indent(out) << "fields: while true";
+  
+  block_open(out);
+  
+  out << endl;
+
+  indent(out) << "let (_, fieldType, fieldID) = try __proto.readFieldBegin()" << endl << endl;
+  indent(out) << "switch (fieldID, fieldType)";
+  
+  block_open(out);
+  
+  indent(out) << "case (_, .STOP):" << endl;
+  indent_up();
+  indent(out) << "break fields" << endl << endl;
+  indent_down();
+  
+  // Generate deserialization code for known cases
+  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
+
+    indent(out) << "case (" << (*f_iter)->get_key() << ", " << type_to_enum((*f_iter)->get_type()) << "):" << endl;
+    indent_up();
+    indent(out) << (*f_iter)->get_name() << " = try __proto.readValue() as " << type_name((*f_iter)->get_type()) << endl << endl;
+    indent_down();
+    
+  }
+
+  indent(out) << "case let (_, unknownType):" << endl;
+  indent_up();
+  indent(out) << "try __proto.skipType(unknownType)" << endl;
+  indent_down();
+  
+  block_close(out);
+  
+  out << endl;
+
+  // Read field end marker
+  indent(out) << "try __proto.readFieldEnd()" << endl;
+  
+  block_close(out);
+
+  out << endl;
+  
+  indent(out) << "try __proto.readStructEnd()" << endl;
+
+  out << endl;
+  
+  if (struct_has_required_fields(tstruct)) {
+    // performs various checks (e.g. check that all required fields are set)
+    indent(out) << "// Required fields" << endl;
+    
+    for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
+      if (field_is_optional(*f_iter)) {
+        continue;
+      }
+      indent(out) << "try __proto.validateValue(" << (*f_iter)->get_name() << ", "
+                  << "named: \"" << (*f_iter)->get_name() << "\")" << endl;
+    }
+  }
+  
+  out << endl;
+    
+  indent(out) << "return " << tstruct->get_name() << "(";
+  for (f_iter = fields.begin(); f_iter != fields.end();) {
+    out << (*f_iter)->get_name() << ": " << (*f_iter)->get_name();
+    if (++f_iter != fields.end()) {
+      out << ", ";
+    }
+  }
+  out << ")" << endl;
+
+  block_close(out);
+
+  out << endl;
+}
+
+/**
+ * Generates a function to write a struct to
+ * a protocol. (TStruct compliance)
+ *
+ * @param tstruct The structure definition
+ * @param is_private
+ *                Is the struct public or private
+ */
+void t_swift_generator::generate_swift_struct_writer(ofstream& out,
+                                                     t_struct* tstruct,
+                                                     bool is_private) {
+  
+  string visibility = is_private ? "private" : "public";
+  
+  indent(out) << visibility << " static func writeValue(__value: " << tstruct->get_name() << ", toProtocol __proto: TProtocol) throws";
+  
+  block_open(out);
+  
+  out << endl;
+
+  string name = tstruct->get_name();
+  const vector<t_field*>& fields = tstruct->get_members();
+  vector<t_field*>::const_iterator f_iter;
+
+  indent(out) << "try __proto.writeStructBeginWithName(\"" << name << "\")" << endl;
+  
+  out << endl;
+  
+  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
+    t_field *tfield = *f_iter;
+    
+    bool optional = field_is_optional(tfield);
+    if (optional) {
+      indent(out) << "if let " << tfield->get_name() << " = __value." << tfield->get_name();
+      block_open(out);
+    }
+    
+    indent(out) << "try __proto.writeFieldValue("
+                << (optional ? "" : "__value.") << tfield->get_name() << ", "
+                << "name: \"" << tfield->get_name() << "\", "
+                << "type: " << type_to_enum(tfield->get_type()) << ", "
+                << "id: " << tfield->get_key() << ")" << endl;
+
+    if (optional) {
+      block_close(out);
+    }
+
+    out << endl;
+  }
+
+  indent(out) << "try __proto.writeFieldStop()" << endl << endl;
+  
+  indent(out) << "try __proto.writeStructEnd()" << endl;
+
+  block_close(out);
+
+  out << endl;
+}
+
+/**
+ * Generates a function to read a struct from
+ * from a protocol. (TStruct compliance)
+ *
+ * This is specifically a function result. Only
+ * the first available field is written.
+ *
+ * @param tstruct The structure definition
+ */
+void t_swift_generator::generate_swift_struct_result_writer(ofstream& out, t_struct* tstruct) {
+  
+  indent(out) << "private static func writeValue(__value: " << tstruct->get_name() << ", toProtocol __proto: TProtocol) throws";
+  
+  block_open(out);
+  
+  out << endl;
+  
+  string name = tstruct->get_name();
+  const vector<t_field*>& fields = tstruct->get_members();
+  vector<t_field*>::const_iterator f_iter;
+  
+  indent(out) << "try __proto.writeStructBeginWithName(\"" << name << "\")" << endl;
+  
+  out << endl;
+  
+  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
+    t_field *tfield = *f_iter;
+    
+    indent(out) << "if let result = __value." << (*f_iter)->get_name();
+    
+    block_open(out);
+    
+    indent(out) << "try __proto.writeFieldValue(result, "
+                << "name: \"" << tfield->get_name() << "\", "
+                << "type: " << type_to_enum(tfield->get_type()) << ", "
+                << "id: " << tfield->get_key() << ")" << endl;
+
+    block_close(out);
+  }
+  // Write the struct map
+  indent(out) << "try __proto.writeFieldStop()" << endl << endl;
+  
+  indent(out) << "try __proto.writeStructEnd()" << endl;
+
+  block_close(out);
+  
+  out << endl;
+}
+
+/**
+ * Generates a description method for the given struct
+ *
+ * @param tstruct The struct definition
+ */
+void t_swift_generator::generate_swift_struct_printable_extension(ofstream& out, t_struct* tstruct) {
+  
+  // Allow use of debugDescription so the app can add description via a cateogory/extension
+
+  indent(out) << "extension " << tstruct->get_name() << " : "
+              << (debug_descriptions_ ? "CustomDebugStringConvertible" : "CustomStringConvertible");
+
+  block_open(out);
+  
+  out << endl;
+  
+  indent(out) << "public var description : String";
+  
+  block_open(out);
+  
+  indent(out) << "var desc = \"" << tstruct->get_name() << "(\"" << endl;
+  
+  const vector<t_field*>& fields = tstruct->get_members();
+  vector<t_field*>::const_iterator f_iter;
+
+  for (f_iter = fields.begin(); f_iter != fields.end();) {
+    indent(out) << "desc += \"" << (*f_iter)->get_name() << "=\\(self." << (*f_iter)->get_name() << ")";
+    if (++f_iter != fields.end()) {
+      out << ", ";
+    }
+    out << "\"" << endl;
+  }
+  indent(out) << "desc += \")\"" << endl;
+  indent(out) << "return desc" << endl;
+
+  block_close(out);
+  
+  out << endl;
+  
+  block_close(out);
+  
+  out << endl;
+}
+
+/**
+ * Generates a thrift service.  In Swift this consists of a
+ * protocol definition and a client (with it's implementation
+ * separated into exts file).
+ *
+ * @param tservice The service definition
+ */
+void t_swift_generator::generate_service(t_service* tservice) {
+  
+  generate_swift_service_protocol(f_decl_, tservice);
+  generate_swift_service_client(f_decl_, tservice);
+  if (async_clients_) {
+    generate_swift_service_protocol_async(f_decl_, tservice);
+    generate_swift_service_client_async(f_decl_, tservice);
+  }
+  generate_swift_service_server(f_decl_, tservice);
+
+  generate_swift_service_helpers(tservice);
+  
+  generate_swift_service_client_implementation(f_impl_, tservice);
+  if (async_clients_) {
+    generate_swift_service_client_async_implementation(f_impl_, tservice);
+  }
+  generate_swift_service_server_implementation(f_impl_, tservice);
+}
+
+/**
+ * Generates structs for all the service return types
+ *
+ * @param tservice The service
+ */
+void t_swift_generator::generate_swift_service_helpers(t_service* tservice) {
+  vector<t_function*> functions = tservice->get_functions();
+  vector<t_function*>::iterator f_iter;
+  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
+    
+    t_struct* ts = (*f_iter)->get_arglist();
+    
+    string qname = function_args_helper_struct_type(tservice, *f_iter);
+    
+    t_struct qname_ts = t_struct(ts->get_program(), qname);
+
+    const vector<t_field*>& members = ts->get_members();
+    vector<t_field*>::const_iterator m_iter;
+    for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
+      qname_ts.append(*m_iter);
+    }
+    
+    generate_swift_struct(f_impl_, &qname_ts, true);
+    generate_swift_struct_implementation(f_impl_, &qname_ts, false, true);
+    generate_function_helpers(tservice, *f_iter);
+  }
+}
+
+string t_swift_generator::function_result_helper_struct_type(t_service *tservice, t_function* tfunction) {
+  if (tfunction->is_oneway()) {
+    return tservice->get_name() + "_" + tfunction->get_name();
+  } else {
+    return tservice->get_name() + "_" + tfunction->get_name() + "_result";
+  }
+}
+
+string t_swift_generator::function_args_helper_struct_type(t_service *tservice, t_function* tfunction) {
+  return tservice->get_name() + "_" + tfunction->get_name() + "_args";
+}
+
+/**
+ * Generates a struct and helpers for a function.
+ *
+ * @param tfunction The function
+ */
+void t_swift_generator::generate_function_helpers(t_service *tservice, t_function* tfunction) {
+  if (tfunction->is_oneway()) {
+    return;
+  }
+
+  // create a result struct with a success field of the return type,
+  // and a field for each type of exception thrown
+  t_struct result(program_, function_result_helper_struct_type(tservice, tfunction));
+  if (!tfunction->get_returntype()->is_void()) {
+    t_field* success = new t_field(tfunction->get_returntype(), "success", 0);
+    success->set_req(t_field::T_OPTIONAL);
+    result.append(success);
+  }
+
+  t_struct* xs = tfunction->get_xceptions();
+  const vector<t_field*>& fields = xs->get_members();
+  vector<t_field*>::const_iterator f_iter;
+  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
+    t_field *x = *f_iter;
+    t_field *ox = new t_field(x->get_type(), x->get_name(), x->get_key());
+    ox->set_req(t_field::T_OPTIONAL);
+    result.append(ox);
+  }
+
+  // generate the result struct
+  generate_swift_struct(f_impl_, &result, true);
+  generate_swift_struct_implementation(f_impl_, &result, true, true);
+  
+  for (f_iter = result.get_members().begin(); f_iter != result.get_members().end(); ++f_iter) {
+    delete *f_iter;
+  }
+}
+
+/**
+ * Generates a service protocol definition.
+ *
+ * @param tservice The service to generate a protocol definition for
+ */
+void t_swift_generator::generate_swift_service_protocol(ofstream& out, t_service* tservice) {
+
+  indent(out) << "public protocol " << tservice->get_name();
+
+  block_open(out);
+  
+  vector<t_function*> functions = tservice->get_functions();
+  vector<t_function*>::iterator f_iter;
+  
+  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
+    out << endl;
+    indent(out) << function_signature(*f_iter) << "  // exceptions: ";
+    t_struct* xs = (*f_iter)->get_xceptions();
+    const vector<t_field*>& xceptions = xs->get_members();
+    vector<t_field*>::const_iterator x_iter;
+    for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
+      out << type_name((*x_iter)->get_type()) + ", ";
+    }
+    out << endl;
+  }
+  
+  block_close(out);
+  
+  out << endl;
+}
+
+/**
+ * Generates an asynchronous service protocol definition.
+ *
+ * @param tservice The service to generate a protocol definition for
+ */
+void t_swift_generator::generate_swift_service_protocol_async(ofstream& out, t_service* tservice) {
+  
+  indent(out) << "public protocol " << tservice->get_name() << "Async";
+
+  block_open(out);
+  
+  vector<t_function*> functions = tservice->get_functions();
+  vector<t_function*>::iterator f_iter;
+  
+  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
+    out << endl;
+    indent(out) << async_function_signature(*f_iter) << endl;
+    if (promise_kit_) {
+      indent(out) << promise_function_signature(*f_iter) << endl;
+    }
+    out << endl;
+  }
+  
+  block_close(out);
+  
+  out << endl;
+}
+
+/**
+ * Generates a service client interface definition.
+ *
+ * @param tservice The service to generate a client interface definition for
+ */
+void t_swift_generator::generate_swift_service_client(ofstream& out,
+                                                                t_service* tservice) {
+  
+  indent(out) << "public class " << tservice->get_name() << "Client /* : " << tservice->get_name() << " */";
+  
+  block_open(out);
+  
+  out << endl;
+
+  indent(out) << "let __inProtocol : TProtocol" << endl << endl;
+  
+  indent(out) << "let __outProtocol : TProtocol" << endl << endl;
+  
+  indent(out) << "public init(inoutProtocol: TProtocol)";
+  
+  block_open(out);
+  
+  indent(out) << "__inProtocol = inoutProtocol" << endl;
+         
+  indent(out) << "__outProtocol = inoutProtocol" << endl;
+                
+  block_close(out);
+  
+  out << endl;
+  
+  indent(out) << "public init(inProtocol: TProtocol, outProtocol: TProtocol)";
+  
+  block_open(out);
+  
+  indent(out) << "__inProtocol = inProtocol" << endl;
+  
+  indent(out) << "__outProtocol = outProtocol" << endl;
+  
+  block_close(out);
+  
+  out << endl;
+  
+  block_close(out);
+  
+  out << endl;
+}
+
+/**
+ * Generates a service client interface definition.
+ *
+ * @param tservice The service to generate a client interface definition for
+ */
+void t_swift_generator::generate_swift_service_client_async(ofstream& out,
+                                                                      t_service* tservice) {
+  
+  indent(out) << "public class " << tservice->get_name() << "AsyncClient /* : " << tservice->get_name() << " */";
+  
+  block_open(out);
+  
+  out << endl;
+  
+  indent(out) << "let __protocolFactory : TProtocolFactory" << endl << endl;
+  
+  indent(out) << "let __transportFactory : TAsyncTransportFactory" << endl << endl;
+  
+  indent(out) << "public init(protocolFactory: TProtocolFactory, transportFactory: TAsyncTransportFactory)";
+  
+  block_open(out);
+  
+  indent(out) << "__protocolFactory = protocolFactory" << endl;
+  
+  indent(out) << "__transportFactory = transportFactory" << endl;
+  
+  block_close(out);
+  
+  out << endl;
+  
+  block_close(out);
+  
+  out << endl;
+}
+
+/**
+ * Generates a service server interface definition. In other words, 
+ * the TProcess implementation for the service definition.
+ *
+ * @param tservice The service to generate a client interface definition for
+ */
+void t_swift_generator::generate_swift_service_server(ofstream& out,
+                                                                t_service* tservice) {
+  
+  indent(out) << "public class " << tservice->get_name() << "Processor : NSObject /* " << tservice->get_name() << " */";
+
+  block_open(out);
+  
+  out << endl;
+  
+  out << indent() << "typealias ProcessorHandlerDictionary = "
+                  << "[String: (Int, TProtocol, TProtocol, " << tservice->get_name() << ") throws -> Void]" << endl
+      << endl
+      << indent() << "let service : " << tservice->get_name() << endl
+      << endl
+      << indent() << "public init(service: " << tservice->get_name() << ")";
+  block_open(out);
+  indent(out) << "self.service = service" << endl;
+  block_close(out);
+
+  out << endl;
+
+  block_close(out);
+  
+  out << endl;
+}
+
+/**
+ * Generates a function that will send the arguments
+ * for a service function via a protocol.
+ *
+ * @param tservice  The service to generate
+ * @param tfunction The function to generate
+ * @param needs_protocol
+ *                  Wether the first parameter must be a protocol or if
+ *                  the protocol is to be assumed
+ */
+void t_swift_generator::generate_swift_service_client_send_function_implementation(ofstream& out,
+                                                                                   t_service *tservice,
+                                                                                   t_function* tfunction,
+                                                                                   bool needs_protocol) {
+  
+  string funname = tfunction->get_name();
+
+  t_function send_function(g_type_bool,
+                           "send_" + tfunction->get_name(),
+                           tfunction->get_arglist());
+
+  string argsname = function_args_helper_struct_type(tservice, tfunction);
+  t_struct* arg_struct = tfunction->get_arglist();
+  
+  // Open function
+  indent(out) << "private func " << send_function.get_name() << "(" << argument_list(tfunction->get_arglist(), needs_protocol ? "__outProtocol" : "", true) << ") throws";
+  block_open(out);
+  
+  out << endl;
+
+  // Serialize the request
+  indent(out) << "try __outProtocol.writeMessageBeginWithName(\"" << funname << "\", "
+              << "type: " << (tfunction->is_oneway() ? ".ONEWAY" : ".CALL") << ", "
+              << "sequenceID: 0)" << endl;
+
+  out << endl;
+  
+  indent(out) << "let __args = " << argsname << "(";
+  
+  // write out function parameters
+  
+  const vector<t_field*>& fields = arg_struct->get_members();
+  vector<t_field*>::const_iterator f_iter;
+  
+  for (f_iter = fields.begin(); f_iter != fields.end();) {
+    t_field *tfield = (*f_iter);
+    out << tfield->get_name() << ": " << tfield->get_name();
+    if (++f_iter != fields.end()) {
+      out << ", ";
+    }
+  }
+  out << ")" << endl;
+  indent(out) << "try " << argsname << ".writeValue(__args, toProtocol: __outProtocol)" << endl << endl;
+  
+  indent(out) << "try __outProtocol.writeMessageEnd()" << endl;
+
+  block_close(out);
+  
+  out << endl;
+}
+
+/**
+ * Generates a function that will recv the result for a
+ * service function via a protocol.
+ *
+ * @param tservice  The service to generate
+ * @param tfunction The function to generate
+ * @param needs_protocol
+ *                  Wether the first parameter must be a protocol or if
+ *                  the protocol is to be assumed
+ */
+void t_swift_generator::generate_swift_service_client_recv_function_implementation(ofstream& out,
+                                                                                   t_service* tservice,
+                                                                                   t_function* tfunction,
+                                                                                   bool needs_protocol) {
+  
+  // Open function
+  indent(out) << "private func recv_" << tfunction->get_name() << "(";
+  
+  if (needs_protocol) {
+    out << "__inProtocol: TProtocol";
+  }
+  
+  out << ") throws";
+  
+  if (!tfunction->get_returntype()->is_void()) {
+    out << " -> " << type_name(tfunction->get_returntype());
+  }
+  
+  block_open(out);
+
+  // check for an exception
+  
+  out << endl;
+  
+  indent(out) << "try __inProtocol.readResultMessageBegin() " << endl << endl;
+  
+  string resultname = function_result_helper_struct_type(tservice, tfunction);
+  indent(out);
+  if (!tfunction->get_returntype()->is_void() || !tfunction->get_xceptions()->get_members().empty()) {
+    out << "let __result = ";
+  }
+  out << "try " << resultname << ".readValueFromProtocol(__inProtocol)" << endl << endl;
+  
+  indent(out) << "try __inProtocol.readMessageEnd()" << endl << endl;
+
+  // Careful, only return _result if not a void function
+  if (!tfunction->get_returntype()->is_void()) {
+    indent(out) << "if let __success = __result.success";
+    block_open(out);
+    indent(out) << "return __success" << endl;
+    block_close(out);
+  }
+
+  t_struct* xs = tfunction->get_xceptions();
+  const vector<t_field*>& xceptions = xs->get_members();
+  vector<t_field*>::const_iterator x_iter;
+  
+  for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
+    indent(out) << "if let " << (*x_iter)->get_name() << " = __result." << (*x_iter)->get_name();
+    block_open(out);
+    indent(out) << "throw " << (*x_iter)->get_name() << endl;
+    block_close(out);
+  }
+
+  // If you get here it's an exception, unless a void function
+  if (!tfunction->get_returntype()->is_void()) {
+    indent(out) << "throw NSError(" << endl;
+    indent_up();
+    indent(out) << "domain: TApplicationErrorDomain, " << endl;
+    indent(out) << "code: Int(TApplicationError.MissingResult.rawValue)," << endl;
+    indent(out) << "userInfo: [TApplicationErrorMethodKey: \"" << tfunction->get_name() << "\"])" << endl;
+    indent_down();
+  }
+
+  // Close function
+  block_close(out);
+  
+  out << endl;
+}
+
+/**
+ * Generates an invocation of a given the send function for the
+ * service function.
+ *
+ * @param tfunction The service to generate an implementation for
+ */
+void t_swift_generator::generate_swift_service_client_send_function_invocation(ofstream& out,
+                                                                               t_function* tfunction) {
+  
+  indent(out) << "try send_" << tfunction->get_name() << "(";
+  
+  t_struct* arg_struct = tfunction->get_arglist();
+  
+  const vector<t_field*>& fields = arg_struct->get_members();
+  vector<t_field*>::const_iterator f_iter;
+  
+  for (f_iter = fields.begin(); f_iter != fields.end();) {
+    out << (*f_iter)->get_name() << ": " << (*f_iter)->get_name();
+    if (++f_iter != fields.end()) {
+      out << ", ";
+    }
+  }
+  
+  out << ")" << endl;
+}
+
+/**
+ * Generates an invocation of a given the send function for the
+ * service function. This is for asynchronous protocols.
+ *
+ * @param tfunction The service to generate an implementation for
+ */
+void t_swift_generator::generate_swift_service_client_send_async_function_invocation(ofstream& out,
+                                                                                     t_function* tfunction) {
+  
+  t_struct* arg_struct = tfunction->get_arglist();
+  const vector<t_field*>& fields = arg_struct->get_members();
+  vector<t_field*>::const_iterator f_iter;
+  
+  indent(out) << "try send_" << tfunction->get_name() << "(__protocol";
+  
+  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
+    out << ", " << (*f_iter)->get_name() << ": " << (*f_iter)->get_name();
+  }
+  
+  out << ")" << endl;
+}
+
+/**
+ * Generates a service client protocol implementation via extension.
+ *
+ * @param tservice The service to generate an implementation for
+ */
+void t_swift_generator::generate_swift_service_client_implementation(ofstream& out,
+                                                                     t_service* tservice) {
+  
+  string name = tservice->get_name() + "Client";
+  
+  indent(out) << "extension " << name << " : " << tservice->get_name();
+  
+  block_open(out);
+  
+  out << endl;
+  
+  // generate client method implementations
+  vector<t_function*> functions = tservice->get_functions();
+  vector<t_function*>::const_iterator f_iter;
+  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
+
+    generate_swift_service_client_send_function_implementation(out, tservice, *f_iter, false);
+
+    if (!(*f_iter)->is_oneway()) {
+      generate_swift_service_client_recv_function_implementation(out, tservice, *f_iter, false);
+    }
+
+    // Open function
+    indent(out) << "public " << function_signature(*f_iter);
+    
+    block_open(out);
+    
+    out << endl;
+    
+    generate_swift_service_client_send_function_invocation(out, *f_iter);
+
+    out << endl;
+
+    indent(out) << "try __outProtocol.transport().flush()" << endl << endl;
+    
+    if (!(*f_iter)->is_oneway()) {
+      if ((*f_iter)->get_returntype()->is_void()) {
+        indent(out) << "try recv_" << (*f_iter)->get_name() << "()" << endl;
+      } else {
+        indent(out) << "return try recv_" << (*f_iter)->get_name() << "()" << endl;
+      }
+    }
+    
+    block_close(out);
+    
+    out << endl;
+  }
+
+  block_close(out);
+  
+  out << endl;
+}
+
+/**
+ * Generates a service asynchronous client protocol implementation via extension.
+ *
+ * @param tservice The service to generate an implementation for
+ */
+void t_swift_generator::generate_swift_service_client_async_implementation(ofstream& out,
+                                                                           t_service* tservice) {
+  
+  string name = tservice->get_name() + "AsyncClient";
+  string protocol_name = tservice->get_name() + "Async";
+
+  indent(out) << "extension " << name << " : " << protocol_name;
+  
+  block_open(out);
+  
+  out << endl;
+  
+  // generate client method implementations
+  vector<t_function*> functions = tservice->get_functions();
+  vector<t_function*>::const_iterator f_iter;
+  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
+
+    generate_swift_service_client_send_function_implementation(out, tservice, *f_iter, true);
+
+    if (!(*f_iter)->is_oneway()) {
+      generate_swift_service_client_recv_function_implementation(out, tservice, *f_iter, true);
+    }
+    
+    indent(out) << "public " << async_function_signature(*f_iter);
+    block_open(out);
+    
+    out << endl;
+
+    out << indent() << "let __transport = __transportFactory.newTransport()" << endl
+        << indent() << "let __protocol = __protocolFactory.newProtocolOnTransport(__transport)" << endl
+        << endl;
+
+    generate_swift_service_client_send_async_function_invocation(out, *f_iter);
+    
+    out << endl;
+    
+    indent(out) << "__transport.flushWithCompletion(";
+    
+    if ((*f_iter)->is_oneway()) {
+      out << "success, failure: failure)" << endl;
+    }
+    else {
+      block_open(out);
+      indent(out) << "do";
+      block_open(out);
+
+      indent(out);
+      if (!(*f_iter)->get_returntype()->is_void()) {
+        out << "let result = ";
+      }
+      out << "try self.recv_" << (*f_iter)->get_name() << "(__protocol)" << endl;
+      
+      out << indent() << "success(";
+      if (!(*f_iter)->get_returntype()->is_void()) {
+        out << "result";
+      }
+      out << ")" << endl;
+      
+      block_close(out);
+      indent(out) << "catch let error";
+      block_open(out);
+      indent(out) << "failure(error as NSError)" << endl;
+      block_close(out);
+      block_close(out);
+      indent(out) << ", failure: failure)" << endl;
+    }
+    
+    
+    block_close(out);
+    
+    out << endl;
+
+    // Promise function
+    if (promise_kit_) {
+      
+      indent(out) << "public " << promise_function_signature(*f_iter);
+      block_open(out);
+      
+      out << indent() << "let (__promise, __fulfill, __reject) = Promise<" << type_name((*f_iter)->get_returntype()) << ">.pendingPromise()" << endl << endl
+          << indent() << "let __transport = __transportFactory.newTransport()" << endl
+          << indent() << "let __protocol = __protocolFactory.newProtocolOnTransport(__transport)" << endl
+          << endl;
+      
+      generate_swift_service_client_send_async_function_invocation(out, *f_iter);
+      
+      out << endl;
+      
+      indent(out) << "__transport.flushWithCompletion(";
+      
+      if ((*f_iter)->is_oneway()) {
+        out << "{ __fulfill() }, failure: { __reject($0) })" << endl;
+      }
+      else {
+        block_open(out);
+        indent(out) << "do";
+        block_open(out);
+        
+        indent(out);
+        if (!(*f_iter)->get_returntype()->is_void()) {
+          out << "let result = ";
+        }
+        out << "try self.recv_" << (*f_iter)->get_name() << "(__protocol)" << endl;
+        
+        out << indent() << "__fulfill(";
+        if (!(*f_iter)->get_returntype()->is_void()) {
+          out << "result";
+        }
+        out << ")" << endl;
+        
+        block_close(out);
+        indent(out) << "catch let error";
+        block_open(out);
+        indent(out) << "__reject(error)" << endl;
+        block_close(out);
+        block_close(out);
+        
+        indent(out) << ", failure: { error in " << endl;
+        indent_up();
+        indent(out) << "__reject(error)" << endl;
+        indent_down();
+        indent(out) << "})" << endl;
+      }
+
+      indent(out) << "return __promise" << endl;
+
+      block_close(out);
+      
+      out << endl;
+      
+    }
+    
+  }
+
+  block_close(out);
+
+  out << endl;
+}
+
+/**
+ * Generates a service server implementation.
+ *
+ * Implemented by generating a block for each service function that
+ * handles the processing of that function. The blocks are stored in
+ * a map and looked up via function/message name.
+ *
+ * @param tservice The service to generate an implementation for
+ */
+void t_swift_generator::generate_swift_service_server_implementation(ofstream& out,
+                                                                     t_service* tservice) {
+  
+  string name = tservice->get_name() + "Processor";
+
+  indent(out) << "extension " << name << " : TProcessor";
+  block_open(out);
+  
+  out << endl;
+  
+  indent(out) << "static let processorHandlers : ProcessorHandlerDictionary =";
+  block_open(out);
+  
+  out << endl;
+  
+  out << indent() << "var processorHandlers = ProcessorHandlerDictionary()" << endl << endl;
+  
+  // generate method map for routing incoming calls
+  vector<t_function*> functions = tservice->get_functions();
+  vector<t_function*>::const_iterator f_iter;
+  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
+    
+    t_function* tfunction = *f_iter;
+    
+    string args_type = function_args_helper_struct_type(tservice, *f_iter);
+    
+    out << indent() << "processorHandlers[\"" << tfunction->get_name() << "\"] = { sequenceID, inProtocol, outProtocol, handler in" << endl
+        << endl;
+    
+    indent_up();
+    out << indent() << "let args = try " << args_type << ".readValueFromProtocol(inProtocol)" << endl
+        << endl
+        << indent() << "try inProtocol.readMessageEnd()" << endl
+        << endl;
+    
+    if (!tfunction->is_oneway() ) {
+      string result_type = function_result_helper_struct_type(tservice, tfunction);
+      indent(out) << "var result = " << result_type << "()" << endl;
+    
+      indent(out) << "do";
+      block_open(out);
+    
+      indent(out);
+      if (!tfunction->get_returntype()->is_void()) {
+        out << "result.success = ";
+      }
+      out << "try handler." << function_name(tfunction) << "(";
+    
+      t_struct* arg_struct = tfunction->get_arglist();
+      const vector<t_field*>& fields = arg_struct->get_members();
+      vector<t_field*>::const_iterator f_iter;
+
+      for (f_iter = fields.begin(); f_iter != fields.end();) {
+        string fieldName = (*f_iter)->get_name();
+        if (f_iter != fields.begin()) {
+          out << fieldName << ": ";
+        }
+        out << "args." << fieldName;
+        if (++f_iter != fields.end()) {
+          out << ", ";
+        }
+      }
+      
+      out << ")" << endl;
+      
+      block_close(out);
+      
+      t_struct* xs = tfunction->get_xceptions();
+      const vector<t_field*>& xfields = xs->get_members();
+      vector<t_field*>::const_iterator x_iter;
+      
+      for (x_iter = xfields.begin(); x_iter != xfields.end(); ++x_iter) {
+        indent(out) << "catch let error as " << (*x_iter)->get_type()->get_name();
+        block_open(out);
+        indent(out) << "result." << (*x_iter)->get_name() << " = error" << endl;
+        block_close(out);
+      }
+      
+      indent(out) << "catch let error";
+      block_open(out);
+      out << indent() << "throw error" << endl;
+      block_close(out);
+      
+      out << endl;
+      
+      if (!tfunction->is_oneway()) {
+        out << indent() << "try outProtocol.writeMessageBeginWithName(\"" << tfunction->get_name() << "\", type: .REPLY, sequenceID: sequenceID)" << endl
+            << indent() << "try " << result_type << ".writeValue(result, toProtocol: outProtocol)" << endl
+            << indent() << "try outProtocol.writeMessageEnd()" << endl;
+      }
+    }
+    block_close(out);
+    
+  }
+  
+  indent(out) << "return processorHandlers" << endl;
+  
+  block_close(out,false);
+  out << "()" << endl;
+  
+  out << endl;
+  
+  indent(out) << "public func processOnInputProtocol(inProtocol: TProtocol, outputProtocol outProtocol: TProtocol) throws";
+  block_open(out);
+  
+  out << endl;
+  
+  out << indent() << "let (messageName, _, sequenceID) = try inProtocol.readMessageBegin()" << endl
+      << endl
+      << indent() << "if let processorHandler = " << name << ".processorHandlers[messageName]";
+  block_open(out);
+  out << indent() << "do";
+  block_open(out);
+  out << indent() << "try processorHandler(sequenceID, inProtocol, outProtocol, service)" << endl;
+  block_close(out);
+  out << indent() << "catch let error as NSError";
+  block_open(out);
+  out << indent() << "try outProtocol.writeExceptionForMessageName(messageName, sequenceID: sequenceID, ex: error)" << endl;
+  block_close(out);
+  block_close(out);
+  out << indent() << "else";
+  block_open(out);
+  out << indent() << "try inProtocol.skipType(.STRUCT)" << endl
+      << indent() << "try inProtocol.readMessageEnd()" << endl
+      << indent() << "try outProtocol.writeExceptionForMessageName(messageName," << endl;
+  indent_up();
+  out << indent() << "sequenceID: sequenceID," << endl
+      << indent() << "ex: NSError(" << endl;
+  indent_up();
+  out << indent() << "domain: TApplicationErrorDomain, " << endl
+      << indent() << "code: Int(TApplicationError.UnknownMethod.rawValue), " << endl
+      << indent() << "userInfo: [TApplicationErrorMethodKey: messageName]))" << endl;
+  indent_down();
+  indent_down();
+  block_close(out);
+  
+  block_close(out);
+  
+  block_close(out);
+  out << endl;
+}
+
+/**
+ * Returns an Swift name
+ *
+ * @param ttype The type
+ * @param class_ref Do we want a Class reference istead of a type reference?
+ * @return Swift type name, i.e. Dictionary<Key,Value>
+ */
+string t_swift_generator::type_name(t_type* ttype, bool is_optional, bool is_forced) {
+  string result;
+  if (ttype->is_base_type()) {
+    result = base_type_name((t_base_type*)ttype);
+  } else if (ttype->is_map()) {
+    t_map *map = (t_map *)ttype;
+    result = "TMap<" + type_name(map->get_key_type()) + ", " + type_name(map->get_val_type()) + ">";
+  } else if (ttype->is_set()) {
+    t_set *set = (t_set *)ttype;
+    result = "TSet<" + type_name(set->get_elem_type()) + ">";
+  } else if (ttype->is_list()) {
+    t_list *list = (t_list *)ttype;
+    result = "TList<" + type_name(list->get_elem_type()) + ">";
+  }
+  else {
+    result = ttype->get_name();
+  }
+  
+  if (is_optional) {
+    result += "?";
+  }
+  
+  if (is_forced) {
+    result += "!";
+  }
+  
+  return result;
+}
+
+/**
+ * Returns the Swift type that corresponds to the thrift type.
+ *
+ * @param tbase The base type
+ */
+string t_swift_generator::base_type_name(t_base_type* type) {
+  t_base_type::t_base tbase = type->get_base();
+
+  switch (tbase) {
+  case t_base_type::TYPE_VOID:
+    return "Void";
+  case t_base_type::TYPE_STRING:
+    if (type->is_binary()) {
+      return "TBinary";
+    } else {
+      return "String";
+    }
+  case t_base_type::TYPE_BOOL:
+    return "Bool";
+  case t_base_type::TYPE_BYTE:
+    return "Int8";
+  case t_base_type::TYPE_I16:
+    return "Int16";
+  case t_base_type::TYPE_I32:
+    return "Int32";
+  case t_base_type::TYPE_I64:
+    return "Int64";
+  case t_base_type::TYPE_DOUBLE:
+    return "Double";
+  default:
+    throw "compiler error: no Swift name for base type " + t_base_type::t_base_name(tbase);
+  }
+}
+
+/**
+ * Renders full constant value (as would be seen after an '=')
+ *
+ */
+void t_swift_generator::render_const_value(ostream& out,
+                                             t_type* type,
+                                             t_const_value* value) {
+  type = get_true_type(type);
+  
+  if (type->is_base_type()) {
+    t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
+    switch (tbase) {
+    case t_base_type::TYPE_STRING:
+      out << "\"" << get_escaped_string(value) << "\"";
+      break;
+    case t_base_type::TYPE_BOOL:
+      out << ((value->get_integer() > 0) ? "true" : "false");
+      break;
+    case t_base_type::TYPE_BYTE:
+    case t_base_type::TYPE_I16:
+    case t_base_type::TYPE_I32:
+    case t_base_type::TYPE_I64:
+      out << type_name(type) << "(" << value->get_integer() << ")";
+      break;
+    case t_base_type::TYPE_DOUBLE:
+      out << type_name(type) << "(";
+      if (value->get_type() == t_const_value::CV_INTEGER) {
+        out << value->get_integer();
+      } else {
+        out << value->get_double();
+      }
+      out << ")";
+      break;
+    default:
+      throw "compiler error: no const of base type " + t_base_type::t_base_name(tbase);
+    }
+  } else if (type->is_enum()) {
+    out << value->get_identifier();
+  } else if (type->is_struct() || type->is_xception()) {
+    
+    out << type_name(type) << "(";
+    
+    const vector<t_field*>& fields = ((t_struct*)type)->get_members();
+    vector<t_field*>::const_iterator f_iter;
+    
+    const map<t_const_value*, t_const_value*>& val = value->get_map();
+    map<t_const_value*, t_const_value*>::const_iterator v_iter;
+
+    for (f_iter = fields.begin(); f_iter != fields.end();) {
+      t_field* tfield = *f_iter;
+      t_const_value* value = NULL;
+      for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
+        if (tfield->get_name() == v_iter->first->get_string()) {
+          value = v_iter->second;
+        }
+      }
+      
+      if (value) {
+        out << tfield->get_name() << ": ";
+        render_const_value(out, tfield->get_type(), value);
+      }
+      else if (!field_is_optional(tfield)) {
+        throw "constant error: required field " + type->get_name() + "." + tfield->get_name() + " has no value";
+      }
+      
+      if (++f_iter != fields.end()) {
+        out << ", ";
+      }
+    }
+    
+    out << ")";
+    
+  } else if (type->is_map()) {
+    
+    out << "[";
+    
+    t_type* ktype = ((t_map*)type)->get_key_type();
+    t_type* vtype = ((t_map*)type)->get_val_type();
+
+    const map<t_const_value*, t_const_value*>& val = value->get_map();
+    map<t_const_value*, t_const_value*>::const_iterator v_iter;
+
+    for (v_iter = val.begin(); v_iter != val.end();) {
+    
+      render_const_value(out, ktype, v_iter->first);
+      out << ": ";
+      render_const_value(out, vtype, v_iter->second);
+      
+      if (++v_iter != val.end()) {
+        out << ", ";
+      }
+    }
+    
+    out << "]";
+    
+  } else if (type->is_list()) {
+    
+    out << "[";
+    
+    t_type* etype = ((t_list*)type)->get_elem_type();
+    
+    const map<t_const_value*, t_const_value*>& val = value->get_map();
+    map<t_const_value*, t_const_value*>::const_iterator v_iter;
+    
+    for (v_iter = val.begin(); v_iter != val.end();) {
+      
+      render_const_value(out, etype, v_iter->first);
+      
+      if (++v_iter != val.end()) {
+        out << ", ";
+      }
+    }
+    
+    out << "]";
+
+  } else if (type->is_set()) {
+
+    out << "[";
+    
+    t_type* etype = ((t_set*)type)->get_elem_type();
+    
+    const map<t_const_value*, t_const_value*>& val = value->get_map();
+    map<t_const_value*, t_const_value*>::const_iterator v_iter;
+    
+    for (v_iter = val.begin(); v_iter != val.end();) {
+      
+      render_const_value(out, etype, v_iter->first);
+      
+      if (++v_iter != val.end()) {
+        out << ", ";
+      }
+    }
+    
+    out << "]";
+    
+  } else {
+    throw "compiler error: no const of type " + type->get_name();
+  }
+
+}
+
+/**
+ * Declares an Swift property.
+ *
+ * @param tfield The field to declare a property for
+ */
+string t_swift_generator::declare_property(t_field* tfield, bool is_private) {
+  
+  string visibility = is_private ? "private" : "public";
+  
+  ostringstream render;
+
+  render << visibility << " var " << tfield->get_name();
+  
+  if (field_is_optional(tfield)) {
+    render << " : " << type_name(tfield->get_type(), true);
+  }
+  else {
+    render << " = " << type_name(tfield->get_type(), false) << "()";
+  }
+  
+  return render.str();
+}
+
+/**
+ * Renders a function signature
+ *
+ * @param tfunction Function definition
+ * @return String of rendered function definition
+ */
+string t_swift_generator::function_signature(t_function* tfunction) {
+  
+  string result = "func " + function_name(tfunction);
+  
+  result += "(" + argument_list(tfunction->get_arglist(), "", false) + ") throws";
+  
+  t_type* ttype = tfunction->get_returntype();
+  if (!ttype->is_void()) {
+    result += " -> " + type_name(ttype);
+  }
+  
+  return result;
+}
+
+/**
+ * Renders a function signature that returns asynchronously via blocks.
+ *
+ * @param tfunction Function definition
+ * @return String of rendered function definition
+ */
+string t_swift_generator::async_function_signature(t_function* tfunction) {
+  t_type* ttype = tfunction->get_returntype();
+  t_struct* targlist = tfunction->get_arglist();
+  string response_param = "(" + ((ttype->is_void()) ? "" : type_name(ttype)) + ") -> Void";
+  string result = "func " + function_name(tfunction);
+  result += "(" + argument_list(tfunction->get_arglist(), "", false)
+          + (targlist->get_members().size() ? ", " : "")
+          + "success: " + response_param + ", "
+          + "failure: (NSError) -> Void) throws";
+  return result;
+}
+
+/**
+ * Renders a function signature that returns asynchronously via promises.
+ *
+ * @param tfunction Function definition
+ * @return String of rendered function definition
+ */
+string t_swift_generator::promise_function_signature(t_function* tfunction) {
+  return "func " + function_name(tfunction) + "(" + argument_list(tfunction->get_arglist(), "", false) + ") throws "
+          + "-> Promise<" + type_name(tfunction->get_returntype()) + ">";
+}
+
+/**
+ * Renders a verbose function name suitable for a Swift method
+ */
+string t_swift_generator::function_name(t_function* tfunction) {
+  string name = tfunction->get_name();
+  if (!tfunction->get_arglist()->get_members().empty()) {
+    string first_arg = tfunction->get_arglist()->get_members().front()->get_name();
+    if (name.size() < first_arg.size() ||
+        lowercase(name.substr(name.size()-first_arg.size())) != lowercase(first_arg)) {
+      name += "With" + capitalize(tfunction->get_arglist()->get_members()[0]->get_name());
+    }
+  }
+  return name;
+}
+
+/**
+ * Renders a Swift method argument list
+ */
+string t_swift_generator::argument_list(t_struct* tstruct, string protocol_name, bool is_internal) {
+  string result = "";
+  bool include_protocol = !protocol_name.empty();
+
+  const vector<t_field*>& fields = tstruct->get_members();
+  vector<t_field*>::const_iterator f_iter;
+  
+  if (include_protocol) {
+    result += protocol_name + ": TProtocol";
+    if (!fields.empty()) {
+      result += ", ";
+    }
+  }
+  else if (!fields.empty() && is_internal) {
+    // Force first argument to be named
+    result += fields.front()->get_name() + " ";
+  }
+  
+  for (f_iter = fields.begin(); f_iter != fields.end();) {
+    t_field* arg = *f_iter;
+    result += arg->get_name() + ": " + type_name(arg->get_type());
+    
+    if (++f_iter != fields.end()) {
+      result += ", ";
+    }
+  }
+  return result;
+}
+
+/**
+ * Converts the parse type to a Swift TType enumeration.
+ */
+string t_swift_generator::type_to_enum(t_type* type, bool qualified) {
+  type = get_true_type(type);
+  
+  string result = qualified ? "TType." : ".";
+
+  if (type->is_base_type()) {
+    t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
+    switch (tbase) {
+    case t_base_type::TYPE_VOID:
+      throw "NO T_VOID CONSTRUCT";
+    case t_base_type::TYPE_STRING:
+      return result + "STRING";
+    case t_base_type::TYPE_BOOL:
+      return result + "BOOL";
+    case t_base_type::TYPE_BYTE:
+      return result + "BYTE";
+    case t_base_type::TYPE_I16:
+      return result + "I16";
+    case t_base_type::TYPE_I32:
+      return result + "I32";
+    case t_base_type::TYPE_I64:
+      return result + "I64";
+    case t_base_type::TYPE_DOUBLE:
+      return result + "DOUBLE";
+    }
+  } else if (type->is_enum()) {
+    return result + "I32";
+  } else if (type->is_struct() || type->is_xception()) {
+    return result + "STRUCT";
+  } else if (type->is_map()) {
+    return result + "MAP";
+  } else if (type->is_set()) {
+    return result + "SET";
+  } else if (type->is_list()) {
+    return result + "LIST";
+  }
+
+  throw "INVALID TYPE IN type_to_enum: " + type->get_name();
+}
+
+
+THRIFT_REGISTER_GENERATOR(
+    swift,
+    "Swift",
+    "    log_unexpected:  Log every time an unexpected field ID or type is encountered.\n"
+    "    async_clients:   Generate clients which invoke asynchronously via block syntax.\n"
+    "    promise_kit:     Generate clients which invoke asynchronously via promises.\n")

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/TApplicationError.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/TApplicationError.h b/lib/cocoa/src/TApplicationError.h
new file mode 100644
index 0000000..079881a
--- /dev/null
+++ b/lib/cocoa/src/TApplicationError.h
@@ -0,0 +1,55 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#import "TProtocol.h"
+
+extern NSString *TApplicationErrorDomain;
+
+typedef NS_ENUM (int, TApplicationError) {
+  TApplicationErrorUnknown                = 0,
+  TApplicationErrorUnknownMethod          = 1,
+  TApplicationErrorInvalidMessageType     = 2,
+  TApplicationErrorWrongMethodName        = 3,
+  TApplicationErrorBadSequenceId          = 4,
+  TApplicationErrorMissingResult          = 5,
+  TApplicationErrorInternalError          = 6,
+  TApplicationErrorProtocolError          = 7,
+  TApplicationErrorInvalidTransform       = 8,
+  TApplicationErrorInvalidProtocol        = 9,
+  TApplicationErrorUnsupportedClientType  = 10,
+};
+
+
+extern NSString *TApplicationErrorNameKey;
+extern NSString *TApplicationErrorReasonKey;
+extern NSString *TApplicationErrorMethodKey;
+
+
+@interface NSError (TApplicationError)
+
+@property (readonly, copy) NSString *name;
+@property (readonly, copy) NSString *reason;
+
++(instancetype) errorWithType:(TApplicationError)type reason:(NSString *)reason;
+
++(instancetype) read:(id<TProtocol>)protocol;
+
+-(BOOL) write:(id<TProtocol>)outProtocol error:(NSError *__autoreleasing *)error;
+
+@end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/TApplicationError.m
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/TApplicationError.m b/lib/cocoa/src/TApplicationError.m
new file mode 100644
index 0000000..080bc0b
--- /dev/null
+++ b/lib/cocoa/src/TApplicationError.m
@@ -0,0 +1,231 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#import "TApplicationError.h"
+#import "TProtocolUtil.h"
+
+
+NSString *TApplicationErrorDomain = @"TApplicationErrorDomain";
+
+
+NSString *TApplicationErrorNameKey = @"name";
+NSString *TApplicationErrorReasonKey = @"reason";
+NSString *TApplicationErrorMethodKey = @"method";
+
+
+@implementation NSError (TApplicationError)
+
+-(NSString *) reason
+{
+  return self.userInfo[TApplicationErrorReasonKey];
+}
+
+-(NSString *) name
+{
+  return self.userInfo[TApplicationErrorNameKey];
+}
+
++(instancetype) errorWithType:(TApplicationError)type reason:(NSString *)reason
+{
+  NSString *name;
+  switch (type) {
+  case TApplicationErrorUnknownMethod:
+    name = @"Unknown Method";
+    break;
+
+  case TApplicationErrorInvalidMessageType:
+    name = @"Invalid Message Type";
+    break;
+
+  case TApplicationErrorWrongMethodName:
+    name = @"Wrong Method Name";
+    break;
+
+  case TApplicationErrorBadSequenceId:
+    name = @"Bad Sequence ID";
+    break;
+
+  case TApplicationErrorMissingResult:
+    name = @"Missing Result";
+    break;
+
+  case TApplicationErrorInternalError:
+    name = @"Internal Error";
+    break;
+
+  case TApplicationErrorProtocolError:
+    name = @"Protocol Error";
+    break;
+
+  case TApplicationErrorInvalidTransform:
+    name = @"Invalid Transform";
+    break;
+
+  case TApplicationErrorInvalidProtocol:
+    name = @"Invalid Protocol";
+    break;
+
+  case TApplicationErrorUnsupportedClientType:
+    name = @"Unsupported Client Type";
+    break;
+
+  default:
+    name = @"Unknown";
+    break;
+  }
+
+  NSDictionary *userInfo;
+  if (reason) {
+    userInfo = @{TApplicationErrorNameKey:name,
+                 TApplicationErrorReasonKey:reason};
+  }
+  else {
+    userInfo = @{TApplicationErrorNameKey:name};
+  }
+
+  return [NSError errorWithDomain:TApplicationErrorDomain
+                             code:type
+                         userInfo:userInfo];
+}
+
+
++(instancetype) read:(id<TProtocol>)protocol
+{
+  NSString *reason = nil;
+  SInt32 type = TApplicationErrorUnknown;
+  SInt32 fieldType;
+  SInt32 fieldID;
+
+  NSError *error;
+  if (![protocol readStructBeginReturningName:NULL error:&error]) {
+    return error;
+  }
+
+  while (true) {
+
+    if (![protocol readFieldBeginReturningName:NULL
+                                          type:&fieldType
+                                       fieldID:&fieldID
+                                         error:&error])
+    {
+      return error;
+    }
+
+    if (fieldType == TTypeSTOP) {
+      break;
+    }
+
+    switch (fieldID) {
+    case 1:
+      if (fieldType == TTypeSTRING) {
+        if (![protocol readString:&reason error:&error]) {
+          return error;
+        }
+      }
+      else {
+        if (![TProtocolUtil skipType:fieldType onProtocol:protocol error:&error]) {
+          return error;
+        }
+      }
+      break;
+
+    case 2:
+      if (fieldType == TTypeI32) {
+        if (![protocol readI32:&type error:&error]) {
+          return error;
+        }
+      }
+      else {
+        if (![TProtocolUtil skipType:fieldType onProtocol:protocol error:&error]) {
+          return error;
+        }
+      }
+      break;
+
+    default:
+      if (![TProtocolUtil skipType:fieldType onProtocol:protocol error:&error]) {
+        return error;
+      }
+      break;
+    }
+    if (![protocol readFieldEnd:&error]) {
+      return error;
+    }
+
+  }
+
+  if (![protocol readStructEnd:&error]) {
+    return error;
+  }
+
+  return [NSError errorWithType:type reason:reason];
+}
+
+
+-(BOOL) write:(id<TProtocol>)protocol error:(NSError *__autoreleasing *)error
+{
+  if (![protocol writeStructBeginWithName:@"TApplicationException" error:error]) {
+    return NO;
+  }
+
+  if (self.localizedDescription != nil) {
+    if (![protocol writeFieldBeginWithName:@"message"
+                                      type:TTypeSTRING
+                                   fieldID:1 error:error])
+    {
+      return NO;
+    }
+
+    if (![protocol writeString:self.localizedDescription error:error]) {
+      return NO;
+    }
+
+    if (![protocol writeFieldEnd:error]) {
+      return NO;
+    }
+  }
+
+  if (![protocol writeFieldBeginWithName:@"type"
+                                    type:TTypeI32
+                                 fieldID:2
+                                   error:error])
+  {
+    return NO;
+  }
+
+  if (![protocol writeI32:(SInt32)self.code error:error]) {
+    return NO;
+  }
+
+  if (![protocol writeFieldEnd:error]) {
+    return NO;
+  }
+
+  if (![protocol writeFieldStop:error]) {
+    return NO;
+  }
+
+  if (![protocol writeStructEnd:error]) {
+    return NO;
+  }
+
+  return YES;
+}
+
+@end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/TApplicationException.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/TApplicationException.h b/lib/cocoa/src/TApplicationException.h
deleted file mode 100644
index 7b027d6..0000000
--- a/lib/cocoa/src/TApplicationException.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#import "TException.h"
-#import "TProtocol.h"
-
-enum {
-  TApplicationException_UNKNOWN = 0,
-  TApplicationException_UNKNOWN_METHOD = 1,
-  TApplicationException_INVALID_MESSAGE_TYPE = 2,
-  TApplicationException_WRONG_METHOD_NAME = 3,
-  TApplicationException_BAD_SEQUENCE_ID = 4,
-  TApplicationException_MISSING_RESULT = 5,
-  TApplicationException_INTERNAL_ERROR = 6,
-  TApplicationException_PROTOCOL_ERROR = 7,
-  TApplicationException_INVALID_TRANSFORM = 8,
-  TApplicationException_INVALID_PROTOCOL = 9,
-  TApplicationException_UNSUPPORTED_CLIENT_TYPE = 10
-};
-
-// FIXME
-@interface TApplicationException : TException {
-  int mType;
-}
-
-+ (TApplicationException *) read: (id <TProtocol>) protocol;
-
-- (void) write: (id <TProtocol>) protocol;
-
-+ (TApplicationException *) exceptionWithType: (int) type
-                                       reason: (NSString *) message;
-
-@end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/TApplicationException.m
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/TApplicationException.m b/lib/cocoa/src/TApplicationException.m
deleted file mode 100644
index 974dfc5..0000000
--- a/lib/cocoa/src/TApplicationException.m
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#import "TApplicationException.h"
-#import "TProtocolUtil.h"
-#import "TObjective-C.h"
-
-@implementation TApplicationException
-
-- (id) initWithType: (int) type
-             reason: (NSString *) reason
-{
-  mType = type;
-
-  NSString * name;
-  switch (type) {
-  case TApplicationException_UNKNOWN_METHOD:
-    name = @"Unknown method";
-    break;
-  case TApplicationException_INVALID_MESSAGE_TYPE:
-    name = @"Invalid message type";
-    break;
-  case TApplicationException_WRONG_METHOD_NAME:
-    name = @"Wrong method name";
-    break;
-  case TApplicationException_BAD_SEQUENCE_ID:
-    name = @"Bad sequence ID";
-    break;
-  case TApplicationException_MISSING_RESULT:
-    name = @"Missing result";
-    break;
-  case TApplicationException_INTERNAL_ERROR:
-    name = @"Internal error";
-    break;
-  case TApplicationException_PROTOCOL_ERROR:
-    name = @"Protocol error";
-    break;
-  case TApplicationException_INVALID_TRANSFORM:
-    name = @"Invalid transform";
-    break;
-  case TApplicationException_INVALID_PROTOCOL:
-    name = @"Invalid protocol";
-    break;
-  case TApplicationException_UNSUPPORTED_CLIENT_TYPE:
-    name = @"Unsupported client type";
-    break;
-  default:
-    name = @"Unknown";
-    break;
-  }
-
-  self = [super initWithName: name reason: reason userInfo: nil];
-  return self;
-}
-
-
-+ (TApplicationException *) read: (id <TProtocol>) protocol
-{
-  NSString * reason = nil;
-  int type = TApplicationException_UNKNOWN;
-  int fieldType;
-  int fieldID;
-
-  [protocol readStructBeginReturningName: NULL];
-
-  while (true) {
-    [protocol readFieldBeginReturningName: NULL
-              type: &fieldType
-              fieldID: &fieldID];
-    if (fieldType == TType_STOP) {
-      break;
-    }
-    switch (fieldID) {
-    case 1:
-      if (fieldType == TType_STRING) {
-        reason = [protocol readString];
-      } else {
-        [TProtocolUtil skipType: fieldType onProtocol: protocol];
-      }
-      break;
-    case 2:
-      if (fieldType == TType_I32) {
-        type = [protocol readI32];
-      } else {
-        [TProtocolUtil skipType: fieldType onProtocol: protocol];
-      }
-      break;
-    default:
-      [TProtocolUtil skipType: fieldType onProtocol: protocol];
-      break;
-    }
-    [protocol readFieldEnd];
-  }
-  [protocol readStructEnd];
-
-  return [TApplicationException exceptionWithType: type reason: reason];
-}
-
-
-- (void) write: (id <TProtocol>) protocol
-{
-  [protocol writeStructBeginWithName: @"TApplicationException"];
-
-  if ([self reason] != nil) {
-    [protocol writeFieldBeginWithName: @"message"
-                 type: TType_STRING
-                 fieldID: 1];
-    [protocol writeString: [self reason]];
-    [protocol writeFieldEnd];
-  }
-
-  [protocol writeFieldBeginWithName: @"type"
-               type: TType_I32
-               fieldID: 2];
-  [protocol writeI32: mType];
-  [protocol writeFieldEnd];
-
-  [protocol writeFieldStop];
-  [protocol writeStructEnd];
-}
-
-
-+ (TApplicationException *) exceptionWithType: (int) type
-                                      reason: (NSString *) reason
-{
-  return [[[TApplicationException alloc] initWithType: type
-                                         reason: reason] autorelease_stub];
-}
-
-@end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/TBaseClient.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/TBaseClient.h b/lib/cocoa/src/TBaseClient.h
index 12944b1..0f73aa0 100644
--- a/lib/cocoa/src/TBaseClient.h
+++ b/lib/cocoa/src/TBaseClient.h
@@ -18,13 +18,10 @@
  */
 
 #import "TProtocol.h"
-#import "TApplicationException.h"
+#import "TApplicationError.h"
 
-@interface TBaseClient : NSObject {
-    id <TProtocol> inProtocol;
-    id <TProtocol> outProtocol;
-}
+@interface TBaseClient : NSObject
 
-- (TApplicationException *)checkIncomingMessageException;
+-(NSError *) checkIncomingMessageException:(id<TProtocol>)protocol;
 
 @end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/TBaseClient.m
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/TBaseClient.m b/lib/cocoa/src/TBaseClient.m
index d15f9d3..249cae0 100644
--- a/lib/cocoa/src/TBaseClient.m
+++ b/lib/cocoa/src/TBaseClient.m
@@ -18,29 +18,34 @@
  */
 
 #import "TBaseClient.h"
-#import "TApplicationException.h"
-#import "TObjective-C.h"
+#import "TApplicationError.h"
+
+
+@interface TBaseClient ()
+@end
+
 
 @implementation TBaseClient
 
-- (void) dealloc
+-(NSError *) checkIncomingMessageException:(id<TProtocol>)inProtocol
 {
-    [inProtocol release_stub];
-    [outProtocol release_stub];
-    [super dealloc_stub];
-}
+  NSError *thriftError;
 
-- (TApplicationException *)checkIncomingMessageException
-{
-    int msgType = 0;
-    [inProtocol readMessageBeginReturningName: nil type: &msgType sequenceID: NULL];
-    if (msgType == TMessageType_EXCEPTION) {
-        TApplicationException * x = [TApplicationException read: inProtocol];
-        [inProtocol readMessageEnd];
-        return x;
-    }
-    
-    return nil;
+  SInt32 msgType = 0;
+  if (![inProtocol readMessageBeginReturningName:nil type:&msgType sequenceID:NULL error:&thriftError]) {
+    return thriftError;
+  }
+
+  if (msgType == TMessageTypeEXCEPTION) {
+
+    thriftError = [NSError read:inProtocol];
+
+    [inProtocol readMessageEnd:NULL];
+
+    return thriftError;
+  }
+
+  return nil;
 }
 
 @end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/TBinary.swift
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/TBinary.swift b/lib/cocoa/src/TBinary.swift
new file mode 100644
index 0000000..c8a3660
--- /dev/null
+++ b/lib/cocoa/src/TBinary.swift
@@ -0,0 +1,122 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import Foundation
+
+
+public struct TBinary : TSerializable {
+  
+  public static var thriftType : TType { return .STRING }
+  
+  private var storage : NSData
+  
+  public init() {
+    self.storage = NSData()
+  }
+  
+  public init(contentsOfFile file: String, options: NSDataReadingOptions = []) throws {
+    self.storage = try NSData(contentsOfFile: file, options: options)
+  }
+  
+  public init(contentsOfURL URL: NSURL, options: NSDataReadingOptions = []) throws {
+    self.storage = try NSData(contentsOfURL: URL, options: options)
+  }
+  
+  public init?(base64EncodedData base64Data: NSData, options: NSDataBase64DecodingOptions = []) {
+    guard let storage = NSData(base64EncodedData: base64Data, options: options) else {
+      return nil
+    }
+    self.storage = storage
+  }
+  
+  public init(data: NSData) {
+    self.storage = data
+  }
+  
+  public var length : Int {
+    return storage.length
+  }
+  
+  public var hashValue : Int {
+    return storage.hashValue
+  }
+  
+  public var bytes : UnsafePointer<Void> {
+    return storage.bytes
+  }
+  
+  public func getBytes(buffer: UnsafeMutablePointer<Void>, length: Int) {
+    storage.getBytes(buffer, length: length)
+  }
+  
+  public func getBytes(buffer: UnsafeMutablePointer<Void>, range: Range<Int>) {
+    storage.getBytes(buffer, range: NSRange(range))
+  }
+  
+  public func subBinaryWithRange(range: Range<Int>) -> TBinary {
+    return TBinary(data: storage.subdataWithRange(NSRange(range)))
+  }
+  
+  public func writeToFile(path: String, options: NSDataWritingOptions = []) throws {
+    try storage.writeToFile(path, options: options)
+  }
+  
+  public func writeToURL(url: NSURL, options: NSDataWritingOptions = []) throws {
+    try storage.writeToURL(url, options: options)
+  }
+  
+  public func rangeOfData(dataToFind data: NSData, options: NSDataSearchOptions, range: Range<Int>) -> Range<Int>? {
+    return storage.rangeOfData(data, options: options, range: NSRange(range)).toRange()
+  }
+  
+  public func enumerateByteRangesUsingBlock(block: (UnsafePointer<Void>, Range<Int>, inout Bool) -> Void) {
+    storage.enumerateByteRangesUsingBlock { bytes, range, stop in
+      var stopTmp = Bool(stop.memory)
+      block(bytes, range.toRange()!, &stopTmp)
+      stop.memory = ObjCBool(stopTmp)
+    }
+  }
+  
+  public static func readValueFromProtocol(proto: TProtocol) throws -> TBinary {
+    var data : NSData?
+    try proto.readBinary(&data)
+    return TBinary(data: data!)
+  }
+  
+  public static func writeValue(value: TBinary, toProtocol proto: TProtocol) throws {
+    try proto.writeBinary(value.storage)
+  }
+  
+}
+
+extension TBinary : CustomStringConvertible, CustomDebugStringConvertible {
+  
+  public var description : String {
+    return storage.description
+  }
+  
+  public var debugDescription : String {
+    return storage.debugDescription
+  }
+  
+}
+
+public func ==(lhs: TBinary, rhs: TBinary) -> Bool {
+  return lhs.storage == rhs.storage
+}


[6/7] thrift git commit: THRIFT-2905 Cocoa compiler should have option to produce "modern" Objective-C Client: Cocoa (ObjectiveC & Swift) Author: Kevin Wooten

Posted by je...@apache.org.
http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/compiler/cpp/src/generate/t_cocoa_generator.cc
----------------------------------------------------------------------
diff --git a/compiler/cpp/src/generate/t_cocoa_generator.cc b/compiler/cpp/src/generate/t_cocoa_generator.cc
index a90c937..f8924bb 100644
--- a/compiler/cpp/src/generate/t_cocoa_generator.cc
+++ b/compiler/cpp/src/generate/t_cocoa_generator.cc
@@ -59,7 +59,16 @@ public:
 
     iter = parsed_options.find("async_clients");
     async_clients_ = (iter != parsed_options.end());
-
+      
+    iter = parsed_options.find("promise_kit");
+    promise_kit_ = (iter != parsed_options.end());
+      
+    iter = parsed_options.find("debug_descriptions");
+    debug_descriptions_ = (iter != parsed_options.end());
+    
+    iter = parsed_options.find("pods");
+    pods_ = (iter != parsed_options.end());
+      
     out_dir_base_ = "gen-cocoa";
   }
 
@@ -108,11 +117,13 @@ public:
   void generate_cocoa_struct_encode_with_coder_method(ofstream& out,
                                                       t_struct* tstruct,
                                                       bool is_exception);
+  void generate_cocoa_struct_copy_method(ofstream& out,
+                                         t_struct* tstruct,
+                                         bool is_exception);
   void generate_cocoa_struct_hash_method(ofstream& out, t_struct* tstruct);
-  void generate_cocoa_struct_is_equal_method(ofstream& out, t_struct* tstruct);
-  void generate_cocoa_struct_field_accessor_declarations(std::ofstream& out,
-                                                         t_struct* tstruct,
-                                                         bool is_exception);
+  void generate_cocoa_struct_is_equal_method(ofstream& out,
+                                             t_struct* tstruct,
+                                             bool is_exception);
   void generate_cocoa_struct_field_accessor_implementations(std::ofstream& out,
                                                             t_struct* tstruct,
                                                             bool is_exception);
@@ -122,9 +133,9 @@ public:
   void generate_cocoa_struct_validator(std::ofstream& out, t_struct* tstruct);
   void generate_cocoa_struct_description(std::ofstream& out, t_struct* tstruct);
 
-  std::string function_result_helper_struct_type(t_function* tfunction);
-  std::string function_args_helper_struct_type(t_function* tfunction);
-  void generate_function_helpers(t_function* tfunction);
+  std::string function_result_helper_struct_type(t_service *tservice, t_function* tfunction);
+  std::string function_args_helper_struct_type(t_service* tservice, t_function* tfunction);
+  void generate_function_helpers(t_service *tservice, t_function* tfunction);
 
   /**
    * Service-level generation functions
@@ -137,10 +148,17 @@ public:
   void generate_cocoa_service_client_async_interface(std::ofstream& out, t_service* tservice);
 
   void generate_cocoa_service_client_send_function_implementation(ofstream& out,
-                                                                  t_function* tfunction);
+                                                                  t_service* tservice,
+                                                                  t_function* tfunction,
+                                                                  bool needs_protocol);
   void generate_cocoa_service_client_send_function_invocation(ofstream& out, t_function* tfunction);
+  void generate_cocoa_service_client_send_async_function_invocation(ofstream& out,
+                                                                    t_function* tfunction,
+                                                                    string failureBlockName);
   void generate_cocoa_service_client_recv_function_implementation(ofstream& out,
-                                                                  t_function* tfunction);
+                                                                  t_service* tservice,
+                                                                  t_function* tfunction,
+                                                                  bool needs_protocol);
   void generate_cocoa_service_client_implementation(std::ofstream& out, t_service* tservice);
   void generate_cocoa_service_client_async_implementation(std::ofstream& out, t_service* tservice);
 
@@ -194,18 +212,25 @@ public:
   std::string cocoa_prefix();
   std::string cocoa_imports();
   std::string cocoa_thrift_imports();
-  std::string type_name(t_type* ttype, bool class_ref = false);
+  std::string type_name(t_type* ttype, bool class_ref = false, bool needs_mutable = false);
   std::string base_type_name(t_base_type* tbase);
-  std::string declare_field(t_field* tfield);
   std::string declare_property(t_field* tfield);
-  std::string function_signature(t_function* tfunction);
-  std::string async_function_signature(t_function* tfunction);
-  std::string argument_list(t_struct* tstruct);
+  std::string declare_property_isset(t_field* tfield);
+  std::string declare_property_unset(t_field* tfield);
+  std::string invalid_return_statement(t_function* tfunction);
+  std::string function_signature(t_function* tfunction, bool include_error);
+  std::string async_function_signature(t_function* tfunction, bool include_error);
+  std::string promise_function_signature(t_function* tfunction);
+  std::string argument_list(t_struct* tstruct, string protocol_name, bool include_error);
   std::string type_to_enum(t_type* ttype);
   std::string format_string_for_type(t_type* type);
+  std::string format_cast_for_type(t_type* type);
   std::string call_field_setter(t_field* tfield, std::string fieldName);
   std::string containerize(t_type* ttype, std::string fieldName);
   std::string decontainerize(t_field* tfield, std::string fieldName);
+  std::string decontainerize(t_type* ttype, std::string fieldName);
+  std::string getter_name(string field_name);
+  std::string setter_name(string field_name);
 
   bool type_can_be_null(t_type* ttype) {
     ttype = get_true_type(ttype);
@@ -217,6 +242,7 @@ public:
 private:
   std::string cocoa_prefix_;
   std::string constants_declarations_;
+  int error_constant_;
 
   /**
    * File streams
@@ -228,6 +254,9 @@ private:
   bool log_unexpected_;
   bool validate_required_;
   bool async_clients_;
+  bool promise_kit_;
+  bool debug_descriptions_;
+  bool pods_;
 };
 
 /**
@@ -240,7 +269,7 @@ void t_cocoa_generator::init_generator() {
   cocoa_prefix_ = program_->get_namespace("cocoa");
 
   // we have a .h header file...
-  string f_header_name = program_name_ + ".h";
+  string f_header_name = cocoa_prefix_ + capitalize(program_name_) + ".h";
   string f_header_fullname = get_out_dir() + f_header_name;
   f_header_.open(f_header_fullname.c_str());
 
@@ -249,13 +278,16 @@ void t_cocoa_generator::init_generator() {
   f_header_ << cocoa_imports() << cocoa_thrift_imports();
 
   // ...and a .m implementation file
-  string f_impl_name = get_out_dir() + program_name_ + ".m";
-  f_impl_.open(f_impl_name.c_str());
+  string f_impl_name = cocoa_prefix_ + capitalize(program_name_) + ".m";
+  string f_impl_fullname = get_out_dir() + f_impl_name;
+  f_impl_.open(f_impl_fullname.c_str());
 
   f_impl_ << autogen_comment() << endl;
 
   f_impl_ << cocoa_imports() << cocoa_thrift_imports() << "#import \"" << f_header_name << "\""
           << endl << endl;
+  
+  error_constant_ = 60000;
 }
 
 /**
@@ -273,25 +305,52 @@ string t_cocoa_generator::cocoa_imports() {
  * @return List of imports necessary for thrift runtime
  */
 string t_cocoa_generator::cocoa_thrift_imports() {
-  string result = string() + "#import \"TProtocol.h\"\n" + "#import \"TApplicationException.h\"\n"
-                  + "#import \"TProtocolException.h\"\n" 
-                  + "#import \"TProtocolUtil.h\"\n"
-                  + "#import \"TProcessor.h\"\n" 
-                  + "#import \"TObjective-C.h\"\n"
-                  + "#import \"TBase.h\"\n"
-                  + "#import \"TAsyncTransport.h\"\n"
-                  + "#import \"TProtocolFactory.h\"\n"
-                  + "#import \"TBaseClient.h\"\n" 
-                  + "\n";
+
+  vector<string> includes_list;
+  includes_list.push_back("TProtocol.h");
+  includes_list.push_back("TProtocolFactory.h");
+  includes_list.push_back("TApplicationError.h");
+  includes_list.push_back("TProtocolError.h");
+  includes_list.push_back("TProtocolUtil.h");
+  includes_list.push_back("TProcessor.h");
+  includes_list.push_back("TBase.h");
+  includes_list.push_back("TAsyncTransport.h");
+  includes_list.push_back("TBaseClient.h");
+
+  std::ostringstream includes;
+
+  vector<string>::const_iterator i_iter;
+  for (i_iter=includes_list.begin(); i_iter!=includes_list.end(); ++i_iter) {
+    includes << "#import ";
+    if (pods_) {
+      includes << "<Thrift/" << *i_iter << ">";
+    } else {
+      includes << "\"" << *i_iter << "\"";
+    }
+    includes << endl;
+  }
+  
+  includes << endl;
+  
+  if (promise_kit_) {
+    includes << "#import ";
+    if (pods_) {
+      includes << "<PromiseKit/PromiseKit.h>";
+    } else {
+      includes << "\"PromiseKit.h\"";
+    }
+    includes << endl;
+  }
 
   // Include other Thrift includes
-  const vector<t_program*>& includes = program_->get_includes();
-  for (size_t i = 0; i < includes.size(); ++i) {
-    result += "#import \"" + includes[i]->get_name() + ".h\"" + "\n";
+  const vector<t_program*>& other_includes = program_->get_includes();
+  for (size_t i = 0; i < other_includes.size(); ++i) {
+    includes << "#import \"" << other_includes[i]->get_name() << ".h\"" << endl;
   }
-  result += "\n";
+  
+  includes << endl;
 
-  return result;
+  return includes.str();
 }
 
 /**
@@ -309,20 +368,46 @@ void t_cocoa_generator::close_generator() {
  * @param ttypedef The type definition
  */
 void t_cocoa_generator::generate_typedef(t_typedef* ttypedef) {
+  if (ttypedef->get_type()->is_map()) {
+    t_map *map = (t_map *)ttypedef->get_type();
+    if (map->get_key_type()->is_struct()) {
+      f_header_ << indent() << "@class " << type_name(map->get_key_type(), true) << ";" << endl;
+    }
+    if (map->get_val_type()->is_struct()) {
+      f_header_ << indent() << "@class " << type_name(map->get_val_type(), true) << ";" << endl;
+    }
+  }
+  else if (ttypedef->get_type()->is_set()) {
+    t_set *set = (t_set *)ttypedef->get_type();
+    if (set->get_elem_type()->is_struct()) {
+      f_header_ << indent() << "@class " << type_name(set->get_elem_type(), true) << ";" << endl;
+    }
+  }
+  else if (ttypedef->get_type()->is_list()) {
+    t_list *list = (t_list *)ttypedef->get_type();
+    if (list->get_elem_type()->is_struct()) {
+      f_header_ << indent() << "@class " << type_name(list->get_elem_type(), true) << ";" << endl;
+    }
+  }
   f_header_ << indent() << "typedef " << type_name(ttypedef->get_type()) << " " << cocoa_prefix_
             << ttypedef->get_symbolic() << ";" << endl << endl;
+  if (ttypedef->get_type()->is_container()) {
+    f_header_ << indent() << "typedef " << type_name(ttypedef->get_type(), false, true) << " " << cocoa_prefix_
+              << "Mutable" << ttypedef->get_symbolic() << ";" << endl << endl;
+  }
 }
 
 /**
  * Generates code for an enumerated type. In Objective-C, this is
- * essentially the same as the thrift definition itself, using the
- * enum keyword in Objective-C.  For namespace purposes, the name of
- * the enum plus an underscore is prefixed onto each element.
+ * essentially the same as the thrift definition itself, instead using
+ * NS_ENUM keyword in Objective-C.  For namespace purposes, the name of
+ * the enum is prefixed to each element in keeping with Cocoa & Swift
+ * standards.
  *
  * @param tenum The enumeration
  */
 void t_cocoa_generator::generate_enum(t_enum* tenum) {
-  f_header_ << indent() << "enum " << cocoa_prefix_ << tenum->get_name() << " {" << endl;
+  f_header_ << indent() << "typedef NS_ENUM(SInt32, " << cocoa_prefix_ << tenum->get_name() << ") {" << endl;
   indent_up();
 
   vector<t_enum_value*> constants = tenum->get_constants();
@@ -334,7 +419,7 @@ void t_cocoa_generator::generate_enum(t_enum* tenum) {
     } else {
       f_header_ << "," << endl;
     }
-    f_header_ << indent() << tenum->get_name() << "_" << (*c_iter)->get_name();
+    f_header_ << indent() << cocoa_prefix_ << tenum->get_name() << (*c_iter)->get_name();
     f_header_ << " = " << (*c_iter)->get_value();
   }
 
@@ -343,36 +428,63 @@ void t_cocoa_generator::generate_enum(t_enum* tenum) {
 }
 
 /**
- * Generates a class that holds all the constants.  Primitive values
- * could have been placed outside this class, but I just put
- * everything in for consistency.
+ * Generates a class that holds all the constants.
  */
 void t_cocoa_generator::generate_consts(std::vector<t_const*> consts) {
   std::ostringstream const_interface;
-  string constants_class_name = cocoa_prefix_ + program_name_ + "Constants";
 
-  const_interface << "@interface " << constants_class_name << " : NSObject ";
-  scope_up(const_interface);
-  scope_down(const_interface);
+  const_interface << "FOUNDATION_EXPORT NSString *" << cocoa_prefix_ << capitalize(program_name_) << "ErrorDomain;" << endl
+                  << endl;
+  
+
+  bool needs_class = false;
 
-  // getter method for each constant defined.
+  // Public constants for base types & strings
   vector<t_const*>::iterator c_iter;
   for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
-    string name = (*c_iter)->get_name();
     t_type* type = (*c_iter)->get_type();
-    const_interface << "+ (" << type_name(type) << ") " << name << ";" << endl;
+    if (!type->is_container() && !type->is_struct()) {
+      const_interface << "FOUNDATION_EXPORT " << type_name(type) << " "
+                      << cocoa_prefix_ << capitalize((*c_iter)->get_name()) << ";" << endl;
+    }
+    else {
+      needs_class = true;
+    }
   }
+  
+  
+  string constants_class_name = cocoa_prefix_ + capitalize(program_name_) + "Constants";
+
+  if (needs_class) {
+
+    const_interface << "@interface " << constants_class_name << " : NSObject ";
+    scope_up(const_interface);
+    scope_down(const_interface);
 
-  const_interface << "@end";
+    // getter method for each constant defined.
+    for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
+      string name = (*c_iter)->get_name();
+      t_type* type = (*c_iter)->get_type();
+      if (type->is_container() || type->is_struct()) {
+        t_type* type = (*c_iter)->get_type();
+        const_interface << "+ (" << type_name(type) << ") " << name << ";" << endl;
+      }
+    }
+
+    const_interface << "@end";
+  }
 
   // this gets spit into the header file in ::close_generator
   constants_declarations_ = const_interface.str();
+  
+  f_impl_ << "NSString *" << cocoa_prefix_ << capitalize(program_name_) << "ErrorDomain = "
+          << "@\"" << cocoa_prefix_ << capitalize(program_name_) << "ErrorDomain\";" << endl << endl;
 
-  // static variables in the .m hold all constant values
+  // variables in the .m hold all simple constant values
   for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
     string name = (*c_iter)->get_name();
     t_type* type = (*c_iter)->get_type();
-    f_impl_ << "static " << type_name(type) << " " << cocoa_prefix_ << name;
+    f_impl_ << type_name(type) << " " << cocoa_prefix_ << name;
     if (!type->is_container() && !type->is_struct()) {
       f_impl_ << " = " << render_const_value(f_impl_, type, (*c_iter)->get_value());
     }
@@ -380,36 +492,40 @@ void t_cocoa_generator::generate_consts(std::vector<t_const*> consts) {
   }
   f_impl_ << endl;
 
-  f_impl_ << "@implementation " << constants_class_name << endl;
+  if (needs_class) {
+    f_impl_ << "@implementation " << constants_class_name << endl;
 
-  // initialize complex constants when the class is loaded
-  f_impl_ << "+ (void) initialize ";
-  scope_up(f_impl_);
+    // initialize complex constants when the class is loaded
+    f_impl_ << "+ (void) initialize ";
+    scope_up(f_impl_);
 
-  for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
-    if ((*c_iter)->get_type()->is_container() || (*c_iter)->get_type()->is_struct()) {
-      print_const_value(f_impl_,
-                        cocoa_prefix_ + (*c_iter)->get_name(),
-                        (*c_iter)->get_type(),
-                        (*c_iter)->get_value(),
-                        false,
-                        false);
-      f_impl_ << ";" << endl;
+    for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
+      if ((*c_iter)->get_type()->is_container() || (*c_iter)->get_type()->is_struct()) {
+        print_const_value(f_impl_,
+                          cocoa_prefix_ + (*c_iter)->get_name(),
+                          (*c_iter)->get_type(),
+                          (*c_iter)->get_value(),
+                          false,
+                          false);
+        f_impl_ << ";" << endl;
+      }
     }
-  }
-  scope_down(f_impl_);
-
-  // getter method for each constant
-  for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
-    string name = (*c_iter)->get_name();
-    t_type* type = (*c_iter)->get_type();
-    f_impl_ << "+ (" << type_name(type) << ") " << name;
-    scope_up(f_impl_);
-    indent(f_impl_) << "return " << cocoa_prefix_ << name << ";" << endl;
     scope_down(f_impl_);
-  }
 
-  f_impl_ << "@end" << endl << endl;
+    // getter method for each constant
+    for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
+      string name = (*c_iter)->get_name();
+      t_type* type = (*c_iter)->get_type();
+      if (type->is_container() || type->is_struct()) {
+        f_impl_ << "+ (" << type_name(type) << ") " << name;
+        scope_up(f_impl_);
+        indent(f_impl_) << "return " << cocoa_prefix_ << name << ";" << endl;
+        scope_down(f_impl_);
+      }
+    }
+
+    f_impl_ << "@end" << endl << endl;
+  }
 }
 
 /**
@@ -441,51 +557,38 @@ void t_cocoa_generator::generate_xception(t_struct* txception) {
 void t_cocoa_generator::generate_cocoa_struct_interface(ofstream& out,
                                                         t_struct* tstruct,
                                                         bool is_exception) {
+  
+  if (is_exception) {
+    out << "enum {" << endl
+        << "  " << cocoa_prefix_ << capitalize(program_name_) << "Error" << tstruct->get_name() <<  " = -" << error_constant_++ << endl
+        << "};" << endl
+        << endl;
+  }
+  
   out << "@interface " << cocoa_prefix_ << tstruct->get_name() << " : ";
 
   if (is_exception) {
-    out << "NSException ";
+    out << "NSError ";
   } else {
     out << "NSObject ";
   }
-  out << "<TBase, NSCoding> ";
-
-  scope_up(out);
-
-  // members are protected.  this is redundant, but explicit.
-  //  f_header_ << endl << "@protected:" << endl;
-
-  const vector<t_field*>& members = tstruct->get_members();
-
-  // member varialbes
-  vector<t_field*>::const_iterator m_iter;
-  for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
-    out << indent() << declare_field(*m_iter) << endl;
-  }
-
-  if (members.size() > 0) {
-    out << endl;
-    // isset fields
-    for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
-      indent(out) << "BOOL __" << (*m_iter)->get_name() << "_isset;" << endl;
-    }
-  }
-
-  scope_down(out);
+  out << "<TBase, NSCoding, NSCopying> " << endl;
+  
   out << endl;
 
   // properties
+  const vector<t_field*>& members = tstruct->get_members();
   if (members.size() > 0) {
-    out << "#if TARGET_OS_IPHONE || (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)"
-        << endl;
+    vector<t_field*>::const_iterator m_iter;
     for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
       out << indent() << declare_property(*m_iter) << endl;
+      out << indent() << declare_property_isset(*m_iter) << endl;
+      out << indent() << declare_property_unset(*m_iter) << endl;
+      out << endl;
     }
-    out << "#endif" << endl << endl;
   }
-
-  // default initializer
-  out << indent() << "- (id) init;" << endl;
+  
+  out << endl;
 
   // initializer for all fields
   if (!members.empty()) {
@@ -494,17 +597,6 @@ void t_cocoa_generator::generate_cocoa_struct_interface(ofstream& out,
   }
   out << endl;
 
-  // read and write
-  out << "- (void) read: (id <TProtocol>) inProtocol;" << endl;
-  out << "- (void) write: (id <TProtocol>) outProtocol;" << endl;
-  out << endl;
-
-  // validator
-  out << "- (void) validate;" << endl << endl;
-
-  // getters and setters
-  generate_cocoa_struct_field_accessor_declarations(out, tstruct, is_exception);
-
   out << "@end" << endl << endl;
 }
 
@@ -516,7 +608,7 @@ void t_cocoa_generator::generate_cocoa_struct_initializer_signature(ofstream& ou
                                                                     t_struct* tstruct) {
   const vector<t_field*>& members = tstruct->get_members();
   vector<t_field*>::const_iterator m_iter;
-  indent(out) << "- (id) initWith";
+  indent(out) << "- (instancetype) initWith";
   for (m_iter = members.begin(); m_iter != members.end();) {
     if (m_iter == members.begin()) {
       out << capitalize((*m_iter)->get_name());
@@ -532,41 +624,25 @@ void t_cocoa_generator::generate_cocoa_struct_initializer_signature(ofstream& ou
 }
 
 /**
- * Generate getter and setter declarations for all fields, plus an
- * IsSet getter.
- */
-void t_cocoa_generator::generate_cocoa_struct_field_accessor_declarations(ofstream& out,
-                                                                          t_struct* tstruct,
-                                                                          bool is_exception) {
-  (void)is_exception;
-  const vector<t_field*>& members = tstruct->get_members();
-  vector<t_field*>::const_iterator m_iter;
-  for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
-    out << indent() << "#if !__has_feature(objc_arc)" << endl;
-    out << indent() << "- (" << type_name((*m_iter)->get_type()) << ") "
-        << decapitalize((*m_iter)->get_name()) << ";" << endl;
-    out << indent() << "- (void) set" << capitalize((*m_iter)->get_name()) << ": ("
-        << type_name((*m_iter)->get_type()) << ") " << (*m_iter)->get_name() << ";" << endl;
-    out << indent() << "#endif" << endl;
-    out << indent() << "- (BOOL) " << (*m_iter)->get_name() << "IsSet;" << endl << endl;
-  }
-}
-
-/**
  * Generate the initWithCoder method for this struct so it's compatible with
  * the NSCoding protocol
  */
 void t_cocoa_generator::generate_cocoa_struct_init_with_coder_method(ofstream& out,
                                                                      t_struct* tstruct,
                                                                      bool is_exception) {
-  indent(out) << "- (id) initWithCoder: (NSCoder *) decoder" << endl;
+
+  indent(out) << "- (instancetype) initWithCoder: (NSCoder *) decoder" << endl;
   scope_up(out);
+  
   if (is_exception) {
     // NSExceptions conform to NSCoding, so we can call super
-    out << indent() << "self = [super initWithCoder: decoder];" << endl;
+    indent(out) << "self = [super initWithCoder: decoder];" << endl;
   } else {
-    out << indent() << "self = [super init];" << endl;
+    indent(out) << "self = [super init];" << endl;
   }
+  
+  indent(out) << "if (self) ";
+  scope_up(out);
 
   const vector<t_field*>& members = tstruct->get_members();
   vector<t_field*>::const_iterator m_iter;
@@ -576,9 +652,9 @@ void t_cocoa_generator::generate_cocoa_struct_init_with_coder_method(ofstream& o
     out << indent() << "if ([decoder containsValueForKey: @\"" << (*m_iter)->get_name() << "\"])"
         << endl;
     scope_up(out);
-    out << indent() << "__" << (*m_iter)->get_name() << " = ";
+    out << indent() << "_" << (*m_iter)->get_name() << " = ";
     if (type_can_be_null(t)) {
-      out << "[[decoder decodeObjectForKey: @\"" << (*m_iter)->get_name() << "\"] retain_stub];"
+      out << "[decoder decodeObjectForKey: @\"" << (*m_iter)->get_name() << "\"];"
           << endl;
     } else if (t->is_enum()) {
       out << "[decoder decodeIntForKey: @\"" << (*m_iter)->get_name() << "\"];" << endl;
@@ -608,9 +684,11 @@ void t_cocoa_generator::generate_cocoa_struct_init_with_coder_method(ofstream& o
             + t_base_type::t_base_name(tbase);
       }
     }
-    out << indent() << "__" << (*m_iter)->get_name() << "_isset = YES;" << endl;
+    out << indent() << "_" << (*m_iter)->get_name() << "IsSet = YES;" << endl;
     scope_down(out);
   }
+  
+  scope_down(out);
 
   out << indent() << "return self;" << endl;
   scope_down(out);
@@ -624,8 +702,10 @@ void t_cocoa_generator::generate_cocoa_struct_init_with_coder_method(ofstream& o
 void t_cocoa_generator::generate_cocoa_struct_encode_with_coder_method(ofstream& out,
                                                                        t_struct* tstruct,
                                                                        bool is_exception) {
+
   indent(out) << "- (void) encodeWithCoder: (NSCoder *) encoder" << endl;
   scope_up(out);
+  
   if (is_exception) {
     // NSExceptions conform to NSCoding, so we can call super
     out << indent() << "[super encodeWithCoder: encoder];" << endl;
@@ -636,40 +716,39 @@ void t_cocoa_generator::generate_cocoa_struct_encode_with_coder_method(ofstream&
 
   for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
     t_type* t = get_true_type((*m_iter)->get_type());
-    out << indent() << "if (__" << (*m_iter)->get_name() << "_isset)" << endl;
+    out << indent() << "if (_" << (*m_iter)->get_name() << "IsSet)" << endl;
     scope_up(out);
-    // out << indent() << "__" << (*m_iter)->get_name() << " = ";
     if (type_can_be_null(t)) {
-      out << indent() << "[encoder encodeObject: __" << (*m_iter)->get_name() << " forKey: @\""
+      out << indent() << "[encoder encodeObject: _" << (*m_iter)->get_name() << " forKey: @\""
           << (*m_iter)->get_name() << "\"];" << endl;
     } else if (t->is_enum()) {
-      out << indent() << "[encoder encodeInt: __" << (*m_iter)->get_name() << " forKey: @\""
+      out << indent() << "[encoder encodeInt: _" << (*m_iter)->get_name() << " forKey: @\""
           << (*m_iter)->get_name() << "\"];" << endl;
     } else {
       t_base_type::t_base tbase = ((t_base_type*)t)->get_base();
       switch (tbase) {
       case t_base_type::TYPE_BOOL:
-        out << indent() << "[encoder encodeBool: __" << (*m_iter)->get_name() << " forKey: @\""
+        out << indent() << "[encoder encodeBool: _" << (*m_iter)->get_name() << " forKey: @\""
             << (*m_iter)->get_name() << "\"];" << endl;
         break;
       case t_base_type::TYPE_BYTE:
-        out << indent() << "[encoder encodeInt: __" << (*m_iter)->get_name() << " forKey: @\""
+        out << indent() << "[encoder encodeInt: _" << (*m_iter)->get_name() << " forKey: @\""
             << (*m_iter)->get_name() << "\"];" << endl;
         break;
       case t_base_type::TYPE_I16:
-        out << indent() << "[encoder encodeInt: __" << (*m_iter)->get_name() << " forKey: @\""
+        out << indent() << "[encoder encodeInt: _" << (*m_iter)->get_name() << " forKey: @\""
             << (*m_iter)->get_name() << "\"];" << endl;
         break;
       case t_base_type::TYPE_I32:
-        out << indent() << "[encoder encodeInt32: __" << (*m_iter)->get_name() << " forKey: @\""
+        out << indent() << "[encoder encodeInt32: _" << (*m_iter)->get_name() << " forKey: @\""
             << (*m_iter)->get_name() << "\"];" << endl;
         break;
       case t_base_type::TYPE_I64:
-        out << indent() << "[encoder encodeInt64: __" << (*m_iter)->get_name() << " forKey: @\""
+        out << indent() << "[encoder encodeInt64: _" << (*m_iter)->get_name() << " forKey: @\""
             << (*m_iter)->get_name() << "\"];" << endl;
         break;
       case t_base_type::TYPE_DOUBLE:
-        out << indent() << "[encoder encodeDouble: __" << (*m_iter)->get_name() << " forKey: @\""
+        out << indent() << "[encoder encodeDouble: _" << (*m_iter)->get_name() << " forKey: @\""
             << (*m_iter)->get_name() << "\"];" << endl;
         break;
       default:
@@ -685,6 +764,38 @@ void t_cocoa_generator::generate_cocoa_struct_encode_with_coder_method(ofstream&
 }
 
 /**
+ * Generate the copy method for this struct
+ */
+void t_cocoa_generator::generate_cocoa_struct_copy_method(ofstream& out, t_struct* tstruct, bool is_exception) {
+  out << indent() << "- (instancetype) copyWithZone:(NSZone *)zone" << endl;
+  scope_up(out);
+  
+  if (is_exception) {
+    out << indent() << type_name(tstruct) << " val = [" << cocoa_prefix_ << tstruct->get_name() << " errorWithDomain: self.domain code: self.code userInfo: self.userInfo];" << endl;
+  } else {
+    out << indent() << type_name(tstruct) << " val = [" << cocoa_prefix_ << tstruct->get_name() << " new];" << endl;
+  }
+  
+  const vector<t_field*>& members = tstruct->get_members();
+  vector<t_field*>::const_iterator m_iter;
+  
+  for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
+    t_type* t = get_true_type((*m_iter)->get_type());
+    if (type_can_be_null(t)) {
+      out << indent() << "val." << (*m_iter)->get_name() << " = [self." << (*m_iter)->get_name() << " copy];";
+    } else {
+      out << indent() << "val." << (*m_iter)->get_name() << " = self." << (*m_iter)->get_name() << ";";
+    }
+    out << endl;
+  }
+  
+  out << indent() << "return val;" << endl;
+  
+  scope_down(out);
+  out << endl;
+}
+
+/**
  * Generate the hash method for this struct
  */
 void t_cocoa_generator::generate_cocoa_struct_hash_method(ofstream& out, t_struct* tstruct) {
@@ -697,14 +808,14 @@ void t_cocoa_generator::generate_cocoa_struct_hash_method(ofstream& out, t_struc
 
   for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
     t_type* t = get_true_type((*m_iter)->get_type());
-    out << indent() << "hash = (hash * 31) ^ __" << (*m_iter)->get_name()
-        << "_isset ? 2654435761 : 0;" << endl;
-    out << indent() << "if (__" << (*m_iter)->get_name() << "_isset)" << endl;
+    out << indent() << "hash = (hash * 31) ^ _" << (*m_iter)->get_name()
+        << "IsSet ? 2654435761 : 0;" << endl;
+    out << indent() << "if (_" << (*m_iter)->get_name() << "IsSet)" << endl;
     scope_up(out);
     if (type_can_be_null(t)) {
-      out << indent() << "hash = (hash * 31) ^ [__" << (*m_iter)->get_name() << " hash];" << endl;
+      out << indent() << "hash = (hash * 31) ^ [_" << (*m_iter)->get_name() << " hash];" << endl;
     } else {
-      out << indent() << "hash = (hash * 31) ^ [@(__" << (*m_iter)->get_name() << ") hash];"
+      out << indent() << "hash = (hash * 31) ^ [@(_" << (*m_iter)->get_name() << ") hash];"
           << endl;
     }
     scope_down(out);
@@ -718,7 +829,7 @@ void t_cocoa_generator::generate_cocoa_struct_hash_method(ofstream& out, t_struc
 /**
  * Generate the isEqual method for this struct
  */
-void t_cocoa_generator::generate_cocoa_struct_is_equal_method(ofstream& out, t_struct* tstruct) {
+void t_cocoa_generator::generate_cocoa_struct_is_equal_method(ofstream& out, t_struct* tstruct, bool is_exception) {
   indent(out) << "- (BOOL) isEqual: (id) anObject" << endl;
   scope_up(out);
 
@@ -730,36 +841,47 @@ void t_cocoa_generator::generate_cocoa_struct_is_equal_method(ofstream& out, t_s
 
   string class_name = cocoa_prefix_ + tstruct->get_name();
 
-  indent(out) << "if (![anObject isKindOfClass:[" << class_name << " class]]) {" << endl;
-  indent_up();
-  indent(out) << "return NO;" << endl;
-  indent_down();
-  indent(out) << "}" << endl;
-
-  indent(out) << class_name << " *other = (" << class_name << " *)anObject;" << endl;
+  if (is_exception) {
+    indent(out) << "if (![super isEqual:anObject]) {" << endl;
+    indent_up();
+    indent(out) << "return NO;" << endl;
+    indent_down();
+    indent(out) << "}" << endl << endl;
+  }
+  else {
+    indent(out) << "if (![anObject isKindOfClass:[" << class_name << " class]]) {" << endl;
+    indent_up();
+    indent(out) << "return NO;" << endl;
+    indent_down();
+    indent(out) << "}" << endl;
+  }
 
   const vector<t_field*>& members = tstruct->get_members();
   vector<t_field*>::const_iterator m_iter;
 
-  for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
-    t_type* t = get_true_type((*m_iter)->get_type());
-    string name = (*m_iter)->get_name();
-    if (type_can_be_null(t)) {
-      out << indent() << "if ((__" << name << "_isset != other->__" << name << "_isset) ||" << endl
-          << indent() << "    "
-          << "(__" << name << "_isset && "
-          << "((__" << name << " || other->__" << name << ") && "
-          << "![__" << name << " isEqual:other->__" << name << "]))) {" << endl;
-    } else {
-      out << indent() << "if ((__" << name << "_isset != other->__" << name << "_isset) ||" << endl
-          << indent() << "    "
-          << "(__" << name << "_isset && "
-          << "(__" << name << " != other->__" << name << "))) {" << endl;
+  if (!members.empty()) {
+    indent(out) << class_name << " *other = (" << class_name << " *)anObject;" << endl;
+    
+    for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
+      t_type* t = get_true_type((*m_iter)->get_type());
+      string name = (*m_iter)->get_name();
+      if (type_can_be_null(t)) {
+        out << indent() << "if ((_" << name << "IsSet != other->_" << name << "IsSet) ||" << endl
+            << indent() << "    "
+            << "(_" << name << "IsSet && "
+            << "((_" << name << " || other->_" << name << ") && "
+            << "![_" << name << " isEqual:other->_" << name << "]))) {" << endl;
+      } else {
+        out << indent() << "if ((_" << name << "IsSet != other->_" << name << "IsSet) ||" << endl
+            << indent() << "    "
+            << "(_" << name << "IsSet && "
+            << "(_" << name << " != other->_" << name << "))) {" << endl;
+      }
+      indent_up();
+      indent(out) << "return NO;" << endl;
+      indent_down();
+      indent(out) << "}" << endl;
     }
-    indent_up();
-    indent(out) << "return NO;" << endl;
-    indent_down();
-    indent(out) << "}" << endl;
   }
 
   out << indent() << "return YES;" << endl;
@@ -785,10 +907,11 @@ void t_cocoa_generator::generate_cocoa_struct_implementation(ofstream& out,
 
   // exceptions need to call the designated initializer on NSException
   if (is_exception) {
-    out << indent() << "- (id) init" << endl;
+    out << indent() << "- (instancetype) init" << endl;
     scope_up(out);
-    out << indent() << "return [super initWithName: @\"" << cocoa_prefix_ << tstruct->get_name()
-        << "\" reason: @\"unknown\" userInfo: nil];" << endl;
+    out << indent() << "return [super initWithDomain: " << cocoa_prefix_ << capitalize(program_name_) << "ErrorDomain" << endl
+        << indent() << "                        code: " << cocoa_prefix_ << capitalize(program_name_) << "Error" << tstruct->get_name() << endl
+        << indent() << "                    userInfo: nil];" << endl;
     scope_down(out);
     out << endl;
   } else {
@@ -796,12 +919,12 @@ void t_cocoa_generator::generate_cocoa_struct_implementation(ofstream& out,
 
     // default initializer
     // setup instance variables with default values
-    indent(out) << "- (id) init" << endl;
+    indent(out) << "- (instancetype) init" << endl;
     scope_up(out);
     indent(out) << "self = [super init];" << endl;
+    indent(out) << "if (self)";
+    scope_up(out);
     if (members.size() > 0) {
-      out << "#if TARGET_OS_IPHONE || (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)"
-          << endl;
       for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
         t_type* t = get_true_type((*m_iter)->get_type());
         if ((*m_iter)->get_value() != NULL) {
@@ -813,8 +936,8 @@ void t_cocoa_generator::generate_cocoa_struct_implementation(ofstream& out,
                             true);
         }
       }
-      out << "#endif" << endl;
     }
+    scope_down(out);
     indent(out) << "return self;" << endl;
     scope_down(out);
     out << endl;
@@ -830,17 +953,19 @@ void t_cocoa_generator::generate_cocoa_struct_implementation(ofstream& out,
     } else {
       out << indent() << "self = [super init];" << endl;
     }
-
+    
+    indent(out) << "if (self)";
+    scope_up(out);
     for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
-      t_type* t = get_true_type((*m_iter)->get_type());
-      out << indent() << "__" << (*m_iter)->get_name() << " = ";
-      if (type_can_be_null(t)) {
-        out << "[" << (*m_iter)->get_name() << " retain_stub];" << endl;
+      out << indent() << "_" << (*m_iter)->get_name() << " = ";
+      if (get_true_type((*m_iter)->get_type())->is_container()) {
+        out << "[" << (*m_iter)->get_name() << " mutableCopy];" << endl;
       } else {
         out << (*m_iter)->get_name() << ";" << endl;
       }
-      out << indent() << "__" << (*m_iter)->get_name() << "_isset = YES;" << endl;
+      out << indent() << "_" << (*m_iter)->get_name() << "IsSet = YES;" << endl;
     }
+    scope_down(out);
 
     out << indent() << "return self;" << endl;
     scope_down(out);
@@ -853,24 +978,9 @@ void t_cocoa_generator::generate_cocoa_struct_implementation(ofstream& out,
   generate_cocoa_struct_encode_with_coder_method(out, tstruct, is_exception);
   // hash and isEqual for NSObject
   generate_cocoa_struct_hash_method(out, tstruct);
-  generate_cocoa_struct_is_equal_method(out, tstruct);
-
-  // dealloc
-  if (!members.empty()) {
-    out << "- (void) dealloc" << endl;
-    scope_up(out);
-
-    for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
-      t_type* t = get_true_type((*m_iter)->get_type());
-      if (type_can_be_null(t)) {
-        indent(out) << "[__" << (*m_iter)->get_name() << " release_stub];" << endl;
-      }
-    }
-
-    out << indent() << "[super dealloc_stub];" << endl;
-    scope_down(out);
-    out << endl;
-  }
+  generate_cocoa_struct_is_equal_method(out, tstruct, is_exception);
+  // copy for NSObject
+  generate_cocoa_struct_copy_method(out, tstruct, is_exception);
 
   // the rest of the methods
   generate_cocoa_struct_field_accessor_implementations(out, tstruct, is_exception);
@@ -892,7 +1002,7 @@ void t_cocoa_generator::generate_cocoa_struct_implementation(ofstream& out,
  * @param tstruct The struct definition
  */
 void t_cocoa_generator::generate_cocoa_struct_reader(ofstream& out, t_struct* tstruct) {
-  out << "- (void) read: (id <TProtocol>) inProtocol" << endl;
+  out << "- (BOOL) read: (id <TProtocol>) inProtocol error: (NSError *__autoreleasing *)__thriftError" << endl;
   scope_up(out);
 
   const vector<t_field*>& fields = tstruct->get_members();
@@ -900,11 +1010,11 @@ void t_cocoa_generator::generate_cocoa_struct_reader(ofstream& out, t_struct* ts
 
   // Declare stack tmp variables
   indent(out) << "NSString * fieldName;" << endl;
-  indent(out) << "int fieldType;" << endl;
-  indent(out) << "int fieldID;" << endl;
+  indent(out) << "SInt32 fieldType;" << endl;
+  indent(out) << "SInt32 fieldID;" << endl;
   out << endl;
 
-  indent(out) << "[inProtocol readStructBeginReturningName: NULL];" << endl;
+  indent(out) << "if (![inProtocol readStructBeginReturningName: NULL error: __thriftError]) return NO;" << endl;
 
   // Loop over reading in fields
   indent(out) << "while (true)" << endl;
@@ -912,11 +1022,11 @@ void t_cocoa_generator::generate_cocoa_struct_reader(ofstream& out, t_struct* ts
 
   // Read beginning field marker
   indent(out)
-      << "[inProtocol readFieldBeginReturningName: &fieldName type: &fieldType fieldID: &fieldID];"
+      << "if (![inProtocol readFieldBeginReturningName: &fieldName type: &fieldType fieldID: &fieldID error: __thriftError]) return NO;"
       << endl;
 
   // Check for field STOP marker and break
-  indent(out) << "if (fieldType == TType_STOP) { " << endl;
+  indent(out) << "if (fieldType == TTypeSTOP) { " << endl;
   indent_up();
   indent(out) << "break;" << endl;
   indent_down();
@@ -936,23 +1046,16 @@ void t_cocoa_generator::generate_cocoa_struct_reader(ofstream& out, t_struct* ts
 
     generate_deserialize_field(out, *f_iter, "fieldValue");
     indent(out) << call_field_setter(*f_iter, "fieldValue") << endl;
-    // if this is an allocated field, release it since the struct
-    // is now retaining it
-    if (type_can_be_null((*f_iter)->get_type())) {
-      // deserialized strings are autorelease, so don't release them
-      if (!(get_true_type((*f_iter)->get_type())->is_string())) {
-        indent(out) << "[fieldValue release_stub];" << endl;
-      }
-    }
 
     indent_down();
     out << indent() << "} else { " << endl;
     if (log_unexpected_) {
       out << indent() << "  NSLog(@\"%s: field ID %i has unexpected type %i.  Skipping.\", "
-                         "__PRETTY_FUNCTION__, fieldID, fieldType);" << endl;
+                         "__PRETTY_FUNCTION__, (int)fieldID, (int)fieldType);" << endl;
     }
-    out << indent() << "  [TProtocolUtil skipType: fieldType onProtocol: inProtocol];" << endl
-        << indent() << "}" << endl << indent() << "break;" << endl;
+    
+    out << indent() << "  if (![TProtocolUtil skipType: fieldType onProtocol: inProtocol error: __thriftError]) return NO;" << endl;
+    out << indent() << "}" << endl << indent() << "break;" << endl;
     indent_down();
   }
 
@@ -960,25 +1063,29 @@ void t_cocoa_generator::generate_cocoa_struct_reader(ofstream& out, t_struct* ts
   out << indent() << "default:" << endl;
   if (log_unexpected_) {
     out << indent() << "  NSLog(@\"%s: unexpected field ID %i with type %i.  Skipping.\", "
-                       "__PRETTY_FUNCTION__, fieldID, fieldType);" << endl;
+                       "__PRETTY_FUNCTION__, (int)fieldID, (int)fieldType);" << endl;
   }
-  out << indent() << "  [TProtocolUtil skipType: fieldType onProtocol: inProtocol];" << endl
-      << indent() << "  break;" << endl;
+
+  out << indent() << "  if (![TProtocolUtil skipType: fieldType onProtocol: inProtocol error: __thriftError]) return NO;" << endl;
+  
+  out << indent() << "  break;" << endl;
 
   scope_down(out);
 
   // Read field end marker
-  indent(out) << "[inProtocol readFieldEnd];" << endl;
+  indent(out) << "if (![inProtocol readFieldEnd: __thriftError]) return NO;" << endl;
 
   scope_down(out);
 
-  out << indent() << "[inProtocol readStructEnd];" << endl;
+  out << indent() << "if (![inProtocol readStructEnd: __thriftError]) return NO;" << endl;
 
   // performs various checks (e.g. check that all required fields are set)
   if (validate_required_) {
-    out << indent() << "[self validate];" << endl;
+    out << indent() << "if (![self validate: __thriftError]) return NO;" << endl;
   }
 
+  indent(out) << "return YES;" << endl;
+  
   indent_down();
   out << indent() << "}" << endl << endl;
 }
@@ -989,33 +1096,33 @@ void t_cocoa_generator::generate_cocoa_struct_reader(ofstream& out, t_struct* ts
  * @param tstruct The struct definition
  */
 void t_cocoa_generator::generate_cocoa_struct_writer(ofstream& out, t_struct* tstruct) {
-  out << indent() << "- (void) write: (id <TProtocol>) outProtocol {" << endl;
+  out << indent() << "- (BOOL) write: (id <TProtocol>) outProtocol error: (NSError *__autoreleasing *)__thriftError {" << endl;
   indent_up();
 
   string name = tstruct->get_name();
   const vector<t_field*>& fields = tstruct->get_members();
   vector<t_field*>::const_iterator f_iter;
 
-  out << indent() << "[outProtocol writeStructBeginWithName: @\"" << name << "\"];" << endl;
+  out << indent() << "if (![outProtocol writeStructBeginWithName: @\"" << name << "\" error: __thriftError]) return NO;" << endl;
 
   for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
-    out << indent() << "if (__" << (*f_iter)->get_name() << "_isset) {" << endl;
+    out << indent() << "if (_" << (*f_iter)->get_name() << "IsSet) {" << endl;
     indent_up();
     bool null_allowed = type_can_be_null((*f_iter)->get_type());
     if (null_allowed) {
-      out << indent() << "if (__" << (*f_iter)->get_name() << " != nil) {" << endl;
+      out << indent() << "if (_" << (*f_iter)->get_name() << " != nil) {" << endl;
       indent_up();
     }
 
-    indent(out) << "[outProtocol writeFieldBeginWithName: @\"" << (*f_iter)->get_name()
+    indent(out) << "if (![outProtocol writeFieldBeginWithName: @\"" << (*f_iter)->get_name()
                 << "\" type: " << type_to_enum((*f_iter)->get_type())
-                << " fieldID: " << (*f_iter)->get_key() << "];" << endl;
+                << " fieldID: " << (*f_iter)->get_key() << " error: __thriftError]) return NO;" << endl;
 
     // Write field contents
-    generate_serialize_field(out, *f_iter, "__" + (*f_iter)->get_name());
+    generate_serialize_field(out, *f_iter, "_" + (*f_iter)->get_name());
 
     // Write field closer
-    indent(out) << "[outProtocol writeFieldEnd];" << endl;
+    indent(out) << "if (![outProtocol writeFieldEnd: __thriftError]) return NO;" << endl;
 
     if (null_allowed) {
       scope_down(out);
@@ -1023,9 +1130,11 @@ void t_cocoa_generator::generate_cocoa_struct_writer(ofstream& out, t_struct* ts
     scope_down(out);
   }
   // Write the struct map
-  out << indent() << "[outProtocol writeFieldStop];" << endl << indent()
-      << "[outProtocol writeStructEnd];" << endl;
+  out << indent() << "if (![outProtocol writeFieldStop: __thriftError]) return NO;" << endl
+      << indent() << "if (![outProtocol writeStructEnd: __thriftError]) return NO;" << endl;
 
+  indent(out) << "return YES;" << endl;
+  
   indent_down();
   out << indent() << "}" << endl << endl;
 }
@@ -1038,14 +1147,14 @@ void t_cocoa_generator::generate_cocoa_struct_writer(ofstream& out, t_struct* ts
  * @param tstruct The struct definition
  */
 void t_cocoa_generator::generate_cocoa_struct_result_writer(ofstream& out, t_struct* tstruct) {
-  out << indent() << "- (void) write: (id <TProtocol>) outProtocol {" << endl;
+  out << indent() << "- (BOOL) write: (id <TProtocol>) outProtocol error: (NSError *__autoreleasing *)__thriftError {" << endl;
   indent_up();
 
   string name = tstruct->get_name();
   const vector<t_field*>& fields = tstruct->get_members();
   vector<t_field*>::const_iterator f_iter;
 
-  out << indent() << "[outProtocol writeStructBeginWithName: @\"" << name << "\"];" << endl;
+  out << indent() << "if (![outProtocol writeStructBeginWithName: @\"" << name << "\" error: __thriftError]) return NO;" << endl;
 
   bool first = true;
   for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
@@ -1056,24 +1165,24 @@ void t_cocoa_generator::generate_cocoa_struct_result_writer(ofstream& out, t_str
       out << " else if ";
     }
 
-    out << "(__" << (*f_iter)->get_name() << "_isset) {" << endl;
+    out << "(_" << (*f_iter)->get_name() << "IsSet) {" << endl;
     indent_up();
 
     bool null_allowed = type_can_be_null((*f_iter)->get_type());
     if (null_allowed) {
-      out << indent() << "if (__" << (*f_iter)->get_name() << " != nil) {" << endl;
+      out << indent() << "if (_" << (*f_iter)->get_name() << " != nil) {" << endl;
       indent_up();
     }
 
-    indent(out) << "[outProtocol writeFieldBeginWithName: @\"" << (*f_iter)->get_name()
+    indent(out) << "if (![outProtocol writeFieldBeginWithName: @\"" << (*f_iter)->get_name()
                 << "\" type: " << type_to_enum((*f_iter)->get_type())
-                << " fieldID: " << (*f_iter)->get_key() << "];" << endl;
+                << " fieldID: " << (*f_iter)->get_key() << " error: __thriftError]) return NO;" << endl;
 
     // Write field contents
-    generate_serialize_field(out, *f_iter, "__" + (*f_iter)->get_name());
+    generate_serialize_field(out, *f_iter, "_" + (*f_iter)->get_name());
 
     // Write field closer
-    indent(out) << "[outProtocol writeFieldEnd];" << endl;
+    indent(out) << "if (![outProtocol writeFieldEnd: __thriftError]) return NO;" << endl;
 
     if (null_allowed) {
       indent_down();
@@ -1084,9 +1193,12 @@ void t_cocoa_generator::generate_cocoa_struct_result_writer(ofstream& out, t_str
     indent(out) << "}";
   }
   // Write the struct map
-  out << endl << indent() << "[outProtocol writeFieldStop];" << endl << indent()
-      << "[outProtocol writeStructEnd];" << endl;
+  out << endl << indent() << "if (![outProtocol writeFieldStop: __thriftError]) return NO;"
+      << endl << indent() << "if (![outProtocol writeStructEnd: __thriftError]) return NO;"
+      << endl;
 
+  indent(out) << "return YES;" << endl;
+  
   indent_down();
   out << indent() << "}" << endl << endl;
 }
@@ -1098,7 +1210,7 @@ void t_cocoa_generator::generate_cocoa_struct_result_writer(ofstream& out, t_str
  * @param tstruct The struct definition
  */
 void t_cocoa_generator::generate_cocoa_struct_validator(ofstream& out, t_struct* tstruct) {
-  out << indent() << "- (void) validate {" << endl;
+  out << indent() << "- (BOOL) validate: (NSError *__autoreleasing *)__thriftError {" << endl;
   indent_up();
 
   const vector<t_field*>& fields = tstruct->get_members();
@@ -1108,13 +1220,19 @@ void t_cocoa_generator::generate_cocoa_struct_validator(ofstream& out, t_struct*
   for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
     t_field* field = (*f_iter);
     if ((*f_iter)->get_req() == t_field::T_REQUIRED) {
-      out << indent() << "if (!__" << field->get_name() << "_isset) {" << endl << indent()
-          << "  @throw [TProtocolException exceptionWithName: @\"TProtocolException\"" << endl
-          << indent() << "                             reason: @\"Required field '"
-          << (*f_iter)->get_name() << "' is not set.\"];" << endl << indent() << "}" << endl;
+      out << indent() << "if (!_" << field->get_name() << "IsSet) ";
+      scope_up(out);
+      indent(out) << "if (__thriftError) ";
+      scope_up(out);
+      out << indent() << "*__thriftError = [NSError errorWithDomain: TProtocolErrorDomain" << endl
+          << indent() << "                                     code: TProtocolErrorUnknown" << endl
+          << indent() << "                                 userInfo: @{TProtocolErrorExtendedErrorKey: @(TProtocolExtendedErrorMissingRequiredField)," << endl
+          << indent() << "                                             TProtocolErrorFieldNameKey: @\"" << (*f_iter)->get_name() << "\"}];" << endl;
+      scope_down(out);
+      scope_down(out);
     }
   }
-
+  indent(out) << "return YES;" << endl;
   indent_down();
   out << indent() << "}" << endl << endl;
 }
@@ -1138,37 +1256,12 @@ void t_cocoa_generator::generate_cocoa_struct_field_accessor_implementations(ofs
     std::string cap_name = field_name;
     cap_name[0] = toupper(cap_name[0]);
 
-    // Simple getter
-    indent(out) << "- (" << type_name(type) << ") ";
-    out << field_name << " {" << endl;
-    indent_up();
-    if (!type_can_be_null(type)) {
-      indent(out) << "return __" << field_name << ";" << endl;
-    } else {
-      indent(out) << "return [[__" << field_name << " retain_stub] autorelease_stub];" << endl;
-    }
-    indent_down();
-    indent(out) << "}" << endl << endl;
-
     // Simple setter
-    indent(out) << "- (void) set" << cap_name << ": (" << type_name(type) << ") " << field_name
+    indent(out) << "- (void) set" << cap_name << ": (" << type_name(type, false, true) << ") " << field_name
                 << " {" << endl;
     indent_up();
-    if (!type_can_be_null(type)) {
-      indent(out) << "__" << field_name << " = " << field_name << ";" << endl;
-    } else {
-      indent(out) << "[" << field_name << " retain_stub];" << endl;
-      indent(out) << "[__" << field_name << " release_stub];" << endl;
-      indent(out) << "__" << field_name << " = " << field_name << ";" << endl;
-    }
-    indent(out) << "__" << field_name << "_isset = YES;" << endl;
-    indent_down();
-    indent(out) << "}" << endl << endl;
-
-    // IsSet
-    indent(out) << "- (BOOL) " << field_name << "IsSet {" << endl;
-    indent_up();
-    indent(out) << "return __" << field_name << "_isset;" << endl;
+    indent(out) << "_" << field_name << " = " << field_name << ";" << endl;
+    indent(out) << "_" << field_name << "IsSet = YES;" << endl;
     indent_down();
     indent(out) << "}" << endl << endl;
 
@@ -1176,10 +1269,9 @@ void t_cocoa_generator::generate_cocoa_struct_field_accessor_implementations(ofs
     indent(out) << "- (void) unset" << cap_name << " {" << endl;
     indent_up();
     if (type_can_be_null(type)) {
-      indent(out) << "[__" << field_name << " release_stub];" << endl;
-      indent(out) << "__" << field_name << " = nil;" << endl;
+      indent(out) << "_" << field_name << " = nil;" << endl;
     }
-    indent(out) << "__" << field_name << "_isset = NO;" << endl;
+    indent(out) << "_" << field_name << "IsSet = NO;" << endl;
     indent_down();
     indent(out) << "}" << endl << endl;
   }
@@ -1191,7 +1283,14 @@ void t_cocoa_generator::generate_cocoa_struct_field_accessor_implementations(ofs
  * @param tstruct The struct definition
  */
 void t_cocoa_generator::generate_cocoa_struct_description(ofstream& out, t_struct* tstruct) {
-  out << indent() << "- (NSString *) description {" << endl;
+  
+  // Allow use of debugDescription so the app can add description via a cateogory/extension
+  if (debug_descriptions_) {
+    out << indent() << "- (NSString *) debugDescription {" << endl;
+  }
+  else {
+    out << indent() << "- (NSString *) description {" << endl;
+  }
   indent_up();
 
   out << indent() << "NSMutableString * ms = [NSMutableString stringWithString: @\""
@@ -1208,8 +1307,8 @@ void t_cocoa_generator::generate_cocoa_struct_description(ofstream& out, t_struc
       indent(out) << "[ms appendString: @\"," << (*f_iter)->get_name() << ":\"];" << endl;
     }
     t_type* ttype = (*f_iter)->get_type();
-    indent(out) << "[ms appendFormat: @\"" << format_string_for_type(ttype) << "\", __"
-                << (*f_iter)->get_name() << "];" << endl;
+    indent(out) << "[ms appendFormat: @\"" << format_string_for_type(ttype) << "\", "
+                << format_cast_for_type(ttype) << "_" << (*f_iter)->get_name() << "];" << endl;
   }
   out << indent() << "[ms appendString: @\")\"];" << endl << indent()
       << "return [NSString stringWithString: ms];" << endl;
@@ -1247,23 +1346,35 @@ void t_cocoa_generator::generate_cocoa_service_helpers(t_service* tservice) {
   vector<t_function*> functions = tservice->get_functions();
   vector<t_function*>::iterator f_iter;
   for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
+    
     t_struct* ts = (*f_iter)->get_arglist();
-    generate_cocoa_struct_interface(f_impl_, ts, false);
-    generate_cocoa_struct_implementation(f_impl_, ts, false, false);
-    generate_function_helpers(*f_iter);
+    
+    string qname = function_args_helper_struct_type(tservice, *f_iter);
+    
+    t_struct qname_ts = t_struct(ts->get_program(), qname);
+
+    const vector<t_field*>& members = ts->get_members();
+    vector<t_field*>::const_iterator m_iter;
+    for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
+      qname_ts.append(*m_iter);
+    }
+    
+    generate_cocoa_struct_interface(f_impl_, &qname_ts, false);
+    generate_cocoa_struct_implementation(f_impl_, &qname_ts, false, false);
+    generate_function_helpers(tservice, *f_iter);
   }
 }
 
-string t_cocoa_generator::function_result_helper_struct_type(t_function* tfunction) {
+string t_cocoa_generator::function_result_helper_struct_type(t_service *tservice, t_function* tfunction) {
   if (tfunction->is_oneway()) {
-    return capitalize(tfunction->get_name());
+    return tservice->get_name() + "_" + tfunction->get_name();
   } else {
-    return capitalize(tfunction->get_name()) + "_result";
+    return tservice->get_name() + "_" + tfunction->get_name() + "_result";
   }
 }
 
-string t_cocoa_generator::function_args_helper_struct_type(t_function* tfunction) {
-  return tfunction->get_name() + "_args";
+string t_cocoa_generator::function_args_helper_struct_type(t_service *tservice, t_function* tfunction) {
+  return tservice->get_name() + "_" + tfunction->get_name() + "_args";
 }
 
 /**
@@ -1271,14 +1382,14 @@ string t_cocoa_generator::function_args_helper_struct_type(t_function* tfunction
  *
  * @param tfunction The function
  */
-void t_cocoa_generator::generate_function_helpers(t_function* tfunction) {
+void t_cocoa_generator::generate_function_helpers(t_service *tservice, t_function* tfunction) {
   if (tfunction->is_oneway()) {
     return;
   }
 
   // create a result struct with a success field of the return type,
   // and a field for each type of exception thrown
-  t_struct result(program_, function_result_helper_struct_type(tfunction));
+  t_struct result(program_, function_result_helper_struct_type(tservice, tfunction));
   t_field success(tfunction->get_returntype(), "success", 0);
   if (!tfunction->get_returntype()->is_void()) {
     result.append(&success);
@@ -1307,7 +1418,7 @@ void t_cocoa_generator::generate_cocoa_service_protocol(ofstream& out, t_service
   vector<t_function*> functions = tservice->get_functions();
   vector<t_function*>::iterator f_iter;
   for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
-    out << "- " << function_signature(*f_iter) << ";"
+    out << "- " << function_signature(*f_iter, true) << ";"
         << "  // throws ";
     t_struct* xs = (*f_iter)->get_xceptions();
     const std::vector<t_field*>& xceptions = xs->get_members();
@@ -1332,7 +1443,10 @@ void t_cocoa_generator::generate_cocoa_service_async_protocol(ofstream& out, t_s
   vector<t_function*> functions = tservice->get_functions();
   vector<t_function*>::iterator f_iter;
   for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
-    out << "- " << async_function_signature(*f_iter) << ";" << endl;
+    out << "- " << async_function_signature(*f_iter, false) << ";" << endl;
+    if (promise_kit_) {
+      out << "- " << promise_function_signature(*f_iter) << ";" << endl;
+    }
   }
   out << "@end" << endl << endl;
 }
@@ -1345,7 +1459,7 @@ void t_cocoa_generator::generate_cocoa_service_async_protocol(ofstream& out, t_s
 void t_cocoa_generator::generate_cocoa_service_client_interface(ofstream& out,
                                                                 t_service* tservice) {
   out << "@interface " << cocoa_prefix_ << tservice->get_name() << "Client : TBaseClient <"
-      << cocoa_prefix_ << tservice->get_name() << "> ";
+      << cocoa_prefix_ << tservice->get_name() << "> " << endl;
 
   out << "- (id) initWithProtocol: (id <TProtocol>) protocol;" << endl;
   out << "- (id) initWithInProtocol: (id <TProtocol>) inProtocol outProtocol: (id <TProtocol>) "
@@ -1361,14 +1475,11 @@ void t_cocoa_generator::generate_cocoa_service_client_interface(ofstream& out,
 void t_cocoa_generator::generate_cocoa_service_client_async_interface(ofstream& out,
                                                                       t_service* tservice) {
   out << "@interface " << cocoa_prefix_ << tservice->get_name() << "ClientAsync : TBaseClient <"
-      << cocoa_prefix_ << tservice->get_name() << "Async> ";
-
-  scope_up(out);
-  out << indent() << "id <TAsyncTransport> asyncTransport;" << endl;
-  scope_down(out);
+      << cocoa_prefix_ << tservice->get_name() << "Async> " << endl
+      << endl;
 
-  out << "- (id) initWithProtocolFactory: (id <TProtocolFactory>) factory "
-         "transport: (id <TAsyncTransport>) transport;" << endl;
+  out << "- (id) initWithProtocolFactory: (id <TProtocolFactory>) protocolFactory "
+      << "transportFactory: (id <TAsyncTransportFactory>) transportFactory;" << endl;
   out << "@end" << endl << endl;
 }
 
@@ -1382,12 +1493,7 @@ void t_cocoa_generator::generate_cocoa_service_client_async_interface(ofstream&
 void t_cocoa_generator::generate_cocoa_service_server_interface(ofstream& out,
                                                                 t_service* tservice) {
   out << "@interface " << cocoa_prefix_ << tservice->get_name()
-      << "Processor : NSObject <TProcessor> ";
-
-  scope_up(out);
-  out << indent() << "id <" << cocoa_prefix_ << tservice->get_name() << "> mService;" << endl;
-  out << indent() << "NSDictionary * mMethodMap;" << endl;
-  scope_down(out);
+      << "Processor : NSObject <TProcessor> " << endl;
 
   out << "- (id) initWith" << tservice->get_name() << ": (id <" << cocoa_prefix_
       << tservice->get_name() << ">) service;" << endl;
@@ -1398,25 +1504,28 @@ void t_cocoa_generator::generate_cocoa_service_server_interface(ofstream& out,
 
 void t_cocoa_generator::generate_cocoa_service_client_send_function_implementation(
     ofstream& out,
-    t_function* tfunction) {
+    t_service *tservice,
+    t_function* tfunction,
+    bool needs_protocol) {
   string funname = tfunction->get_name();
 
-  t_function send_function(g_type_void,
+  t_function send_function(g_type_bool,
                            string("send_") + tfunction->get_name(),
                            tfunction->get_arglist());
 
-  string argsname = tfunction->get_name() + "_args";
+  string argsname = function_args_helper_struct_type(tservice, tfunction);
 
   // Open function
-  indent(out) << "- " << function_signature(&send_function) << endl;
+  indent(out) << "- (BOOL) send_" << tfunction->get_name() << argument_list(tfunction->get_arglist(), needs_protocol ? "outProtocol" : "", true) << endl;
   scope_up(out);
-
+  
   // Serialize the request
-  out << indent() << "[outProtocol writeMessageBeginWithName: @\"" << funname << "\""
-      << (tfunction->is_oneway() ? " type: TMessageType_ONEWAY" : " type: TMessageType_CALL")
-      << " sequenceID: 0];" << endl;
+  out << indent() << "if (![outProtocol writeMessageBeginWithName: @\"" << funname << "\""
+      << (tfunction->is_oneway() ? " type: TMessageTypeONEWAY" : " type: TMessageTypeCALL")
+      << " sequenceID: 0 error: __thriftError]) return NO;" << endl;
 
-  out << indent() << "[outProtocol writeStructBeginWithName: @\"" << argsname << "\"];" << endl;
+  out << indent() << "if (![outProtocol writeStructBeginWithName: @\"" << argsname
+                  << "\" error: __thriftError]) return NO;" << endl;
 
   // write out function parameters
   t_struct* arg_struct = tfunction->get_arglist();
@@ -1428,14 +1537,14 @@ void t_cocoa_generator::generate_cocoa_service_client_send_function_implementati
       out << indent() << "if (" << fieldName << " != nil)";
       scope_up(out);
     }
-    out << indent() << "[outProtocol writeFieldBeginWithName: @\"" << fieldName
+    out << indent() << "if (![outProtocol writeFieldBeginWithName: @\"" << fieldName
         << "\""
            " type: " << type_to_enum((*fld_iter)->get_type())
-        << " fieldID: " << (*fld_iter)->get_key() << "];" << endl;
+        << " fieldID: " << (*fld_iter)->get_key() << " error: __thriftError]) return NO;" << endl;
 
     generate_serialize_field(out, *fld_iter, fieldName);
 
-    out << indent() << "[outProtocol writeFieldEnd];" << endl;
+    out << indent() << "if (![outProtocol writeFieldEnd: __thriftError]) return NO;" << endl;
 
     if (type_can_be_null((*fld_iter)->get_type())) {
       indent_down();
@@ -1443,63 +1552,91 @@ void t_cocoa_generator::generate_cocoa_service_client_send_function_implementati
     }
   }
 
-  out << indent() << "[outProtocol writeFieldStop];" << endl;
-  out << indent() << "[outProtocol writeStructEnd];" << endl;
-  out << indent() << "[outProtocol writeMessageEnd];" << endl;
+  out << indent() << "if (![outProtocol writeFieldStop: __thriftError]) return NO;" << endl;
+  out << indent() << "if (![outProtocol writeStructEnd: __thriftError]) return NO;" << endl;
+  out << indent() << "if (![outProtocol writeMessageEnd: __thriftError]) return NO;" << endl;
+  out << indent() << "return YES;" << endl;
   scope_down(out);
   out << endl;
 }
 
 void t_cocoa_generator::generate_cocoa_service_client_recv_function_implementation(
     ofstream& out,
-    t_function* tfunction) {
-  t_struct noargs(program_);
-  t_function recv_function(tfunction->get_returntype(),
-                           string("recv_") + tfunction->get_name(),
-                           &noargs,
-                           tfunction->get_xceptions());
+    t_service* tservice,
+    t_function* tfunction,
+    bool needs_protocol) {
+
+  
   // Open function
-  indent(out) << "- " << function_signature(&recv_function) << endl;
+  indent(out) << "- (BOOL) recv_" << tfunction->get_name();
+  if (!tfunction->get_returntype()->is_void()) {
+    out << ": (" << type_name(tfunction->get_returntype(), false, true) << " *) result ";
+    if (needs_protocol) {
+      out << "protocol";
+    } else {
+      out << "error";
+    }
+  }
+  if (needs_protocol) {
+    out << ": (id<TProtocol>) inProtocol error";
+  }
+  out << ": (NSError *__autoreleasing *)__thriftError" << endl;
   scope_up(out);
 
   // TODO(mcslee): Message validation here, was the seqid etc ok?
 
   // check for an exception
-  out << indent() << "TApplicationException * x = [self checkIncomingMessageException];" << endl
-      << indent() << "if (x != nil)";
+  out << indent() << "NSError *incomingException = [self checkIncomingMessageException: inProtocol];" << endl
+      << indent() << "if (incomingException)";
+  scope_up(out);
+  out << indent() << "if (__thriftError)";
   scope_up(out);
-  out << indent() << "@throw x;" << endl;
+  out << indent() << "*__thriftError = incomingException;" << endl;
+  scope_down(out);
+  out << indent() << "return NO;" << endl;
   scope_down(out);
 
   // FIXME - could optimize here to reduce creation of temporary objects.
-  string resultname = function_result_helper_struct_type(tfunction);
-  out << indent() << cocoa_prefix_ << resultname << " * result = [[[" << cocoa_prefix_ << resultname
-      << " alloc] init] autorelease_stub];" << endl;
-  indent(out) << "[result read: inProtocol];" << endl;
-  indent(out) << "[inProtocol readMessageEnd];" << endl;
+  string resultname = function_result_helper_struct_type(tservice, tfunction);
+  out << indent() << cocoa_prefix_ << resultname << " * resulter = [" << cocoa_prefix_ << resultname << " new];" << endl;
+  indent(out) << "if (![resulter read: inProtocol error: __thriftError]) return NO;" << endl;
+  indent(out) << "if (![inProtocol readMessageEnd: __thriftError]) return NO;" << endl;
 
   // Careful, only return _result if not a void function
   if (!tfunction->get_returntype()->is_void()) {
-    out << indent() << "if ([result successIsSet]) {" << endl << indent()
-        << "  return [result success];" << endl << indent() << "}" << endl;
+    out << indent() << "if (resulter.successIsSet)";
+    scope_up(out);
+    out << indent() << "*result = resulter.success;" << endl;
+    out << indent() << "return YES;" << endl;
+    scope_down(out);
   }
 
   t_struct* xs = tfunction->get_xceptions();
   const std::vector<t_field*>& xceptions = xs->get_members();
   vector<t_field*>::const_iterator x_iter;
   for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
-    out << indent() << "if ([result " << (*x_iter)->get_name() << "IsSet]) {" << endl << indent()
-        << "  @throw [result " << (*x_iter)->get_name() << "];" << endl << indent() << "}" << endl;
+    out << indent() << "if (resulter." << (*x_iter)->get_name() << "IsSet)";
+    scope_up(out);
+    out << indent() << "if (__thriftError)";
+    scope_up(out);
+    out << indent() << "*__thriftError = [resulter " << (*x_iter)->get_name() << "];" << endl;
+    scope_down(out);
+    out << indent() << "return NO;" << endl;
+    scope_down(out);
   }
 
   // If you get here it's an exception, unless a void function
   if (tfunction->get_returntype()->is_void()) {
-    indent(out) << "return;" << endl;
+    indent(out) << "return YES;" << endl;
   } else {
-    out << indent() << "@throw [TApplicationException exceptionWithType: "
-                       "TApplicationException_MISSING_RESULT" << endl << indent()
-        << "                                         reason: @\"" << tfunction->get_name()
-        << " failed: unknown result\"];" << endl;
+    out << indent() << "if (__thriftError)";
+    scope_up(out);
+    out << indent() << "*__thriftError = [NSError errorWithDomain: TApplicationErrorDomain" << endl
+        << indent() << "                                     code: TApplicationErrorMissingResult" << endl
+        << indent() << "                                 userInfo: @{TApplicationErrorMethodKey: @\""
+        << tfunction->get_name() << "\"}];" << endl;
+    scope_down(out);
+    out << indent() << "return NO;" << endl;
   }
 
   // Close function
@@ -1513,12 +1650,13 @@ void t_cocoa_generator::generate_cocoa_service_client_recv_function_implementati
  * @param tfunction The service to generate an implementation for
  */
 void t_cocoa_generator::generate_cocoa_service_client_send_function_invocation(
-    ofstream& out,
-    t_function* tfunction) {
+                                                                               ofstream& out,
+                                                                               t_function* tfunction) {
+  
   t_struct* arg_struct = tfunction->get_arglist();
   const vector<t_field*>& fields = arg_struct->get_members();
   vector<t_field*>::const_iterator fld_iter;
-  indent(out) << "[self send_" << tfunction->get_name();
+  out << indent() << "if (![self send_" << tfunction->get_name();
   bool first = true;
   for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) {
     string fieldName = (*fld_iter)->get_name();
@@ -1530,7 +1668,45 @@ void t_cocoa_generator::generate_cocoa_service_client_send_function_invocation(
       out << fieldName << ": " << fieldName;
     }
   }
-  out << "];" << endl;
+  if (!fields.empty()) {
+    out << " error";
+  }
+  out << ": __thriftError]) " << invalid_return_statement(tfunction) << endl;
+}
+
+/**
+ * Generates an invocation of a given 'send_' function.
+ *
+ * @param tfunction The service to generate an implementation for
+ */
+void t_cocoa_generator::generate_cocoa_service_client_send_async_function_invocation(
+                                                                                     ofstream& out,
+                                                                                     t_function* tfunction,
+                                                                                     string failureBlockName) {
+  
+  t_struct* arg_struct = tfunction->get_arglist();
+  const vector<t_field*>& fields = arg_struct->get_members();
+  vector<t_field*>::const_iterator fld_iter;
+  out << indent() << "if (![self send_" << tfunction->get_name();
+  bool first = true;
+  for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) {
+    string fieldName = (*fld_iter)->get_name();
+    out << " ";
+    if (first) {
+      first = false;
+      out << ": " << fieldName;
+    } else {
+      out << fieldName << ": " << fieldName;
+    }
+  }
+  if (!fields.empty()) {
+    out << " protocol";
+  }
+  out << ": protocol error: &thriftError]) ";
+  scope_up(out);
+  out << indent() << failureBlockName << "(thriftError);" << endl
+      << indent() << "return;" << endl;
+  scope_down(out);
 }
 
 /**
@@ -1540,7 +1716,20 @@ void t_cocoa_generator::generate_cocoa_service_client_send_function_invocation(
  */
 void t_cocoa_generator::generate_cocoa_service_client_implementation(ofstream& out,
                                                                      t_service* tservice) {
-  out << "@implementation " << cocoa_prefix_ << tservice->get_name() << "Client" << endl;
+  
+  string name = cocoa_prefix_ + tservice->get_name() + "Client";
+  
+  out << "@interface " << name << " () ";
+  scope_up(out);
+  out << endl;
+  out << indent() << "id<TProtocol> inProtocol;" << endl;
+  out << indent() << "id<TProtocol> outProtocol;" << endl;
+  out << endl;
+  scope_down(out);
+  out << endl;
+  out << "@end" << endl << endl;
+  
+  out << "@implementation " << name << endl;
 
   // initializers
   out << "- (id) initWithProtocol: (id <TProtocol>) protocol" << endl;
@@ -1553,8 +1742,11 @@ void t_cocoa_generator::generate_cocoa_service_client_implementation(ofstream& o
          "anOutProtocol" << endl;
   scope_up(out);
   out << indent() << "self = [super init];" << endl;
-  out << indent() << "inProtocol = [anInProtocol retain_stub];" << endl;
-  out << indent() << "outProtocol = [anOutProtocol retain_stub];" << endl;
+  out << indent() << "if (self) ";
+  scope_up(out);
+  out << indent() << "inProtocol = anInProtocol;" << endl;
+  out << indent() << "outProtocol = anOutProtocol;" << endl;
+  scope_down(out);
   out << indent() << "return self;" << endl;
   scope_down(out);
   out << endl;
@@ -1564,29 +1756,40 @@ void t_cocoa_generator::generate_cocoa_service_client_implementation(ofstream& o
   vector<t_function*>::const_iterator f_iter;
   for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
 
-    generate_cocoa_service_client_send_function_implementation(out, *f_iter);
+    generate_cocoa_service_client_send_function_implementation(out, tservice, *f_iter, false);
 
     if (!(*f_iter)->is_oneway()) {
-      generate_cocoa_service_client_recv_function_implementation(out, *f_iter);
+      generate_cocoa_service_client_recv_function_implementation(out, tservice, *f_iter, false);
     }
 
     // Open function
-    indent(out) << "- " << function_signature(*f_iter) << endl;
+    indent(out) << "- " << function_signature(*f_iter, true) << endl;
     scope_up(out);
     generate_cocoa_service_client_send_function_invocation(out, *f_iter);
 
-    out << indent() << "[[outProtocol transport] flush];" << endl;
+    out << indent() << "if (![[outProtocol transport] flush: __thriftError]) " << invalid_return_statement(*f_iter) << endl;
     if (!(*f_iter)->is_oneway()) {
-      out << indent();
-      if (!(*f_iter)->get_returntype()->is_void()) {
-        out << "return ";
+      if ((*f_iter)->get_returntype()->is_void()) {
+        out << indent() << "if (![self recv_" << (*f_iter)->get_name() << ": __thriftError]) return NO;" << endl;
+        out << indent() << "return YES;" << endl;
+      } else {
+        out << indent() << type_name((*f_iter)->get_returntype(), false, true) << " __result;" << endl
+            << indent() << "if (![self recv_" << (*f_iter)->get_name() << ": &__result error: __thriftError]) "
+            << invalid_return_statement(*f_iter) << endl;
+        if (type_can_be_null((*f_iter)->get_returntype())) {
+          out << indent() << "return __result;" << endl;
+        } else {
+          out << indent() << "return @(__result);" << endl;
+        }
       }
-      out << "[self recv_" << (*f_iter)->get_name() << "];" << endl;
+    }
+    else {
+      out << indent() << "return YES;" << endl;
     }
     scope_down(out);
     out << endl;
   }
-  indent_down();
+
   out << "@end" << endl << endl;
 }
 
@@ -1597,16 +1800,30 @@ void t_cocoa_generator::generate_cocoa_service_client_implementation(ofstream& o
  */
 void t_cocoa_generator::generate_cocoa_service_client_async_implementation(ofstream& out,
                                                                            t_service* tservice) {
-  out << "@implementation " << cocoa_prefix_ << tservice->get_name() << "ClientAsync" << endl
-      << endl << "- (id) initWithProtocolFactory: (id <TProtocolFactory>) factory "
-                 "transport: (id <TAsyncTransport>) transport;" << endl;
+  
+  string name = cocoa_prefix_ + tservice->get_name() + "ClientAsync";
+
+  out << "@interface " << name << " () ";
+  scope_up(out);
+  out << endl;
+  out << indent() << "id<TProtocolFactory> protocolFactory;" << endl;
+  out << indent() << "id<TAsyncTransportFactory> transportFactory;" << endl;
+  out << endl;
+  scope_down(out);
+  out << endl;
+  out << "@end" << endl << endl;
+  
+  
+  out << "@implementation " << name << endl
+      << endl << "- (id) initWithProtocolFactory: (id <TProtocolFactory>) aProtocolFactory "
+                 "transportFactory: (id <TAsyncTransportFactory>) aTransportFactory;" << endl;
 
   scope_up(out);
   out << indent() << "self = [super init];" << endl;
-  out << indent() << "inProtocol = [[factory newProtocolOnTransport:transport] retain_stub];"
-      << endl;
-  out << indent() << "outProtocol = inProtocol;" << endl;
-  out << indent() << "asyncTransport = transport;" << endl;
+  out << indent() << "if (self) {" << endl;
+  out << indent() << "  protocolFactory = aProtocolFactory;" << endl;
+  out << indent() << "  transportFactory = aTransportFactory;" << endl;
+  out << indent() << "}" << endl;
   out << indent() << "return self;" << endl;
   scope_down(out);
   out << endl;
@@ -1616,57 +1833,120 @@ void t_cocoa_generator::generate_cocoa_service_client_async_implementation(ofstr
   vector<t_function*>::const_iterator f_iter;
   for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
 
-    generate_cocoa_service_client_send_function_implementation(out, *f_iter);
+    generate_cocoa_service_client_send_function_implementation(out, tservice, *f_iter, true);
 
     if (!(*f_iter)->is_oneway()) {
-      generate_cocoa_service_client_recv_function_implementation(out, *f_iter);
+      generate_cocoa_service_client_recv_function_implementation(out, tservice, *f_iter, true);
     }
 
     // Open function
-    indent(out) << "- " << async_function_signature(*f_iter) << endl;
+    indent(out) << "- " << async_function_signature(*f_iter, false) << endl;
     scope_up(out);
-    indent(out) << "@try {" << endl;
-    indent_up();
-    generate_cocoa_service_client_send_function_invocation(out, *f_iter);
-    indent_down();
-    out << indent() << "} @catch(TException * texception) {" << endl;
-    indent_up();
-    out << indent() << "failureBlock(texception);" << endl << indent() << "return;" << endl;
-    indent_down();
-    indent(out) << "}" << endl;
-
-    out << indent() << "[asyncTransport flush:^{" << endl;
-    indent_up();
+    
+    out << indent() << "NSError *thriftError;" << endl
+        << indent() << "id<TAsyncTransport> transport = [transportFactory newTransport];" << endl
+        << indent() << "id<TProtocol> protocol = [protocolFactory newProtocolOnTransport:transport];" << endl
+        << endl;
+    
+    generate_cocoa_service_client_send_async_function_invocation(out, *f_iter, "failureBlock");
 
-    out << indent() << "@try {" << endl;
+    out << indent() << "[transport flushWithCompletion:^{" << endl;
     indent_up();
 
-    string recv_invocation = "[self recv_" + (*f_iter)->get_name() + "]";
-    if (!(*f_iter)->is_oneway() && (*f_iter)->get_returntype()->is_void()) {
-      out << indent() << recv_invocation << ";" << endl;
+    if (!(*f_iter)->is_oneway()) {
+      out << indent() << "NSError *thriftError;" << endl;
+      
+      if (!(*f_iter)->get_returntype()->is_void()) {
+        out << indent() << type_name((*f_iter)->get_returntype()) << " result;" << endl;
+      }
+      out << indent() << "if (![self recv_" << (*f_iter)->get_name();
+      if (!(*f_iter)->get_returntype()->is_void()) {
+        out << ": &result protocol";
+      }
+      out << ": protocol error: &thriftError]) ";
+      scope_up(out);
+      out << indent() << "failureBlock(thriftError);" << endl
+          << indent() << "return;" << endl;
+      scope_down(out);
     }
+    
     out << indent() << "responseBlock(";
     if (!(*f_iter)->is_oneway() && !(*f_iter)->get_returntype()->is_void()) {
-      out << recv_invocation;
+      out << "result";
     }
     out << ");" << endl;
 
     indent_down();
-
-    out << indent() << "} @catch(TException * texception) {" << endl;
-    indent_up();
-
-    out << indent() << "failureBlock(texception);" << endl;
-
-    indent_down();
-    out << indent() << "}" << endl;
-
-    indent_down();
+    
     out << indent() << "} failure:failureBlock];" << endl;
-
+    
     scope_down(out);
 
     out << endl;
+    
+    // Promise function
+    if (promise_kit_) {
+      
+      indent(out) << "- " << promise_function_signature(*f_iter) << endl;
+      scope_up(out);
+      
+      out << indent() << "return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolver) {" << endl;
+      indent_up();
+      
+      out << indent() << "NSError *thriftError;" << endl
+          << indent() << "id<TAsyncTransport> transport = [transportFactory newTransport];" << endl
+          << indent() << "id<TProtocol> protocol = [protocolFactory newProtocolOnTransport:transport];" << endl
+          << endl;
+      
+      generate_cocoa_service_client_send_async_function_invocation(out, *f_iter, "resolver");
+      
+      out << indent() << "[transport flushWithCompletion:^{" << endl;
+      indent_up();
+      
+      if (!(*f_iter)->is_oneway()) {
+        out << indent() << "NSError *thriftError;" << endl;
+        
+        if (!(*f_iter)->get_returntype()->is_void()) {
+          out << indent() << type_name((*f_iter)->get_returntype()) << " result;" << endl;
+        }
+        out << indent() << "if (![self recv_" << (*f_iter)->get_name();
+        if (!(*f_iter)->get_returntype()->is_void()) {
+          out << ": &result protocol";
+        }
+        out << ": protocol error: &thriftError]) ";
+        scope_up(out);
+        out << indent() << "resolver(thriftError);" << endl
+            << indent() << "return;" << endl;
+        scope_down(out);
+      }
+      
+      out << indent() << "resolver(";
+      if ((*f_iter)->is_oneway() || (*f_iter)->get_returntype()->is_void()) {
+        out << "@YES";
+      } else if (type_can_be_null((*f_iter)->get_returntype())) {
+        out << "result";
+      } else {
+        out << "@(result)";
+      }
+      out << ");" << endl;
+      
+      indent_down();
+      
+      out << indent() << "} failure:^(NSError *error) {" << endl;
+      indent_up();
+      out << indent() << "resolver(error);" << endl;
+      indent_down();
+      out << indent() << "}];" << endl;
+      
+      indent_down();
+      out << indent() << "}];" << endl;
+      
+      scope_down(out);
+      
+      out << endl;
+      
+    }
+    
   }
 
   out << "@end" << endl << endl;
@@ -1680,19 +1960,29 @@ void t_cocoa_generator::generate_cocoa_service_client_async_implementation(ofstr
  */
 void t_cocoa_generator::generate_cocoa_service_server_implementation(ofstream& out,
                                                                      t_service* tservice) {
-  out << "@implementation " << cocoa_prefix_ << tservice->get_name() << "Processor" << endl;
+  
+  string name = cocoa_prefix_ + tservice->get_name() + "Processor";
+  
+  out << "@interface " << name << " () ";
+  
+  scope_up(out);
+  out << indent() << "id <" << cocoa_prefix_ << tservice->get_name() << "> service;" << endl;
+  out << indent() << "NSDictionary * methodMap;" << endl;
+  scope_down(out);
+  
+  out << "@end" << endl << endl;
+  
+  out << "@implementation " << name << endl;
 
   // initializer
   out << endl;
-  out << "- (id) initWith" << tservice->get_name() << ": (id <" << cocoa_prefix_
-      << tservice->get_name() << ">) service" << endl;
+  out << "- (id) initWith" << tservice->get_name() << ": (id <" << cocoa_prefix_ << tservice->get_name() << ">) aService" << endl;
   scope_up(out);
   out << indent() << "self = [super init];" << endl;
-  out << indent() << "if (!self) {" << endl;
-  out << indent() << "  return nil;" << endl;
-  out << indent() << "}" << endl;
-  out << indent() << "mService = [service retain_stub];" << endl;
-  out << indent() << "mMethodMap = [[NSMutableDictionary dictionary] retain_stub];" << endl;
+  out << indent() << "if (self) ";
+  scope_up(out);
+  out << indent() << "service = aService;" << endl;
+  out << indent() << "methodMap = [NSMutableDictionary dictionary];" << endl;
 
   // generate method map for routing incoming calls
   vector<t_function*> functions = tservice->get_functions();
@@ -1700,16 +1990,15 @@ void t_cocoa_generator::generate_cocoa_service_server_implementation(ofstream& o
   for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
     string funname = (*f_iter)->get_name();
     scope_up(out);
-    out << indent() << "SEL s = @selector(process_" << funname
-        << "_withSequenceID:inProtocol:outProtocol:);" << endl;
+    out << indent() << "SEL s = @selector(process_" << funname << "_withSequenceID:inProtocol:outProtocol:error:);" << endl;
     out << indent() << "NSMethodSignature * sig = [self methodSignatureForSelector: s];" << endl;
-    out << indent()
-        << "NSInvocation * invocation = [NSInvocation invocationWithMethodSignature: sig];" << endl;
+    out << indent() << "NSInvocation * invocation = [NSInvocation invocationWithMethodSignature: sig];" << endl;
     out << indent() << "[invocation setSelector: s];" << endl;
     out << indent() << "[invocation retainArguments];" << endl;
-    out << indent() << "[mMethodMap setValue: invocation forKey: @\"" << funname << "\"];" << endl;
+    out << indent() << "[methodMap setValue: invocation forKey: @\"" << funname << "\"];" << endl;
     scope_down(out);
   }
+  scope_down(out);
   out << indent() << "return self;" << endl;
   scope_down(out);
 
@@ -1718,33 +2007,36 @@ void t_cocoa_generator::generate_cocoa_service_server_implementation(ofstream& o
   out << endl;
   out << indent() << "- (id<" << cocoa_prefix_ << tservice->get_name() << ">) service" << endl;
   out << indent() << "{" << endl;
-  out << indent() << "  return [[mService retain_stub] autorelease_stub];" << endl;
+  out << indent() << "  return service;" << endl;
   out << indent() << "}" << endl;
 
   // implementation of the TProcess method, which dispatches the incoming call using the method map
   out << endl;
   out << indent() << "- (BOOL) processOnInputProtocol: (id <TProtocol>) inProtocol" << endl;
   out << indent() << "                 outputProtocol: (id <TProtocol>) outProtocol" << endl;
+  out << indent() << "                          error: (NSError *__autoreleasing *)__thriftError" << endl;
   out << indent() << "{" << endl;
   out << indent() << "  NSString * messageName;" << endl;
-  out << indent() << "  int messageType;" << endl;
-  out << indent() << "  int seqID;" << endl;
-  out << indent() << "  [inProtocol readMessageBeginReturningName: &messageName" << endl;
+  out << indent() << "  SInt32 messageType;" << endl;
+  out << indent() << "  SInt32 seqID;" << endl;
+  out << indent() << "  if (![inProtocol readMessageBeginReturningName: &messageName" << endl;
   out << indent() << "                                       type: &messageType" << endl;
-  out << indent() << "                                 sequenceID: &seqID];" << endl;
-  out << indent() << "  NSInvocation * invocation = [mMethodMap valueForKey: messageName];" << endl;
+  out << indent() << "                                 sequenceID: &seqID" << endl;
+  out << indent() << "                                      error: __thriftError]) return NO;" << endl;
+  out << indent() << "  NSInvocation * invocation = [methodMap valueForKey: messageName];" << endl;
   out << indent() << "  if (invocation == nil) {" << endl;
-  out << indent() << "    [TProtocolUtil skipType: TType_STRUCT onProtocol: inProtocol];" << endl;
-  out << indent() << "    [inProtocol readMessageEnd];" << endl;
-  out << indent() << "    TApplicationException * x = [TApplicationException exceptionWithType: "
-                     "TApplicationException_UNKNOWN_METHOD reason: [NSString stringWithFormat: "
-                     "@\"Invalid method name: '%@'\", messageName]];" << endl;
-  out << indent() << "    [outProtocol writeMessageBeginWithName: messageName" << endl;
-  out << indent() << "                                      type: TMessageType_EXCEPTION" << endl;
-  out << indent() << "                                sequenceID: seqID];" << endl;
-  out << indent() << "    [x write: outProtocol];" << endl;
-  out << indent() << "    [outProtocol writeMessageEnd];" << endl;
-  out << indent() << "    [[outProtocol transport] flush];" << endl;
+  out << indent() << "    if (![TProtocolUtil skipType: TTypeSTRUCT onProtocol: inProtocol error: __thriftError]) return NO;" << endl;
+  out << indent() << "    if (![inProtocol readMessageEnd: __thriftError]) return NO;" << endl;
+  out << indent() << "    NSError * x = [NSError errorWithDomain: TApplicationErrorDomain" << endl;
+  out << indent() << "                                      code: TApplicationErrorUnknownMethod" << endl;
+  out << indent() << "                                  userInfo: @{TApplicationErrorMethodKey: messageName}];" << endl;
+  out << indent() << "    if (![outProtocol writeMessageBeginWithName: messageName" << endl;
+  out << indent() << "                                           type: TMessageTypeEXC

<TRUNCATED>

[3/7] thrift git commit: THRIFT-2905 Cocoa compiler should have option to produce "modern" Objective-C Client: Cocoa (ObjectiveC & Swift) Author: Kevin Wooten

Posted by je...@apache.org.
http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/protocol/TCompactProtocol.m
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/protocol/TCompactProtocol.m b/lib/cocoa/src/protocol/TCompactProtocol.m
index 45b0ef3..9b0ebb2 100644
--- a/lib/cocoa/src/protocol/TCompactProtocol.m
+++ b/lib/cocoa/src/protocol/TCompactProtocol.m
@@ -18,14 +18,13 @@
  */
 
 #import "TCompactProtocol.h"
-#import "TObjective-C.h"
-#import "TProtocolException.h"
-
-static const uint8_t COMPACT_PROTOCOL_ID = 0x82;
-static const uint8_t COMPACT_VERSION = 1;
-static const uint8_t COMPACT_VERSION_MASK = 0x1F; // 0001 1111
-static const uint8_t COMPACT_TYPE_MASK = 0xE0; // 1110 0000
-static const uint8_t COMPACT_TYPE_BITS = 0x07; // 0000 0111
+#import "TProtocolError.h"
+
+static const UInt8 COMPACT_PROTOCOL_ID = 0x82;
+static const UInt8 COMPACT_VERSION = 1;
+static const UInt8 COMPACT_VERSION_MASK = 0x1F; // 0001 1111
+static const UInt8 COMPACT_TYPE_MASK = 0xE0; // 1110 0000
+static const UInt8 COMPACT_TYPE_BITS = 0x07; // 0000 0111
 static const int COMPACT_TYPE_SHIFT_AMOUNT = 5;
 
 enum {
@@ -46,322 +45,442 @@ enum {
 
 @implementation TCompactProtocolFactory
 
-+ (TCompactProtocolFactory *) sharedFactory
++(TCompactProtocolFactory *) sharedFactory
 {
-  static TCompactProtocolFactory * gSharedFactory = nil;
+  static TCompactProtocolFactory *gSharedFactory = nil;
   if (gSharedFactory == nil) {
     gSharedFactory = [[TCompactProtocolFactory alloc] init];
   }
-  
+
   return gSharedFactory;
 }
 
-- (TCompactProtocol *) newProtocolOnTransport: (id <TTransport>) transport
+-(NSString *) protocolName
 {
-  return [[TCompactProtocol alloc] initWithTransport: transport];
+  return @"compact";
+}
+
+-(TCompactProtocol *) newProtocolOnTransport:(id <TTransport>)transport
+{
+  return [[TCompactProtocol alloc] initWithTransport:transport];
 }
 
 @end
 
-@implementation TCompactProtocol {
-  NSMutableArray * lastField;
-  short lastFieldId;
-  id <TTransport> mTransport;
-  
-  NSString * boolFieldName;
-  NSNumber * boolFieldType;
-  NSNumber * boolFieldId;
-  NSNumber * booleanValue;
-}
 
-- (id) init
+@interface TCompactProtocol ()
+
+@property(strong, nonatomic) id <TTransport> transport;
+
+@property(strong, nonatomic) NSMutableArray *lastField;
+@property(assign, nonatomic) short lastFieldId;
+
+@property(strong, nonatomic) NSString *boolFieldName;
+@property(strong, nonatomic) NSNumber *boolFieldType;
+@property(strong, nonatomic) NSNumber *boolFieldId;
+@property(strong, nonatomic) NSNumber *booleanValue;
+
+@property(strong, nonatomic) NSString *currentMessageName;
+
+@end
+
+
+@implementation TCompactProtocol
+
+-(id) init
 {
   self = [super init];
-  
+
   if (self != nil) {
-    lastField = [[NSMutableArray alloc] init];
+    _lastField = [[NSMutableArray alloc] init];
   }
-  
+
   return self;
 }
 
-- (id) initWithTransport: (id <TTransport>) transport
+-(id) initWithTransport:(id <TTransport>)aTransport
 {
   self = [self init];
-  
+
   if (self != nil) {
-    mTransport = [transport retain_stub];
+    _transport = aTransport;
   }
-  
+
   return self;
 }
 
-- (void) dealloc
+-(id <TTransport>) transport
 {
-  [lastField release_stub];
-  [mTransport release_stub];
-  [boolFieldName release_stub];
-  [boolFieldType release_stub];
-  [boolFieldId release_stub];
-  [booleanValue release_stub];
-  
-  [super dealloc_stub];
+  return _transport;
 }
 
-- (id <TTransport>) transport
+-(BOOL) writeByteDirect:(UInt8)n error:(NSError *__autoreleasing *)error
 {
-  return mTransport;
+  if (![_transport write:(UInt8 *)&n offset:0 length:1 error:error]) {
+    PROTOCOL_TRANSPORT_ERROR(NO, error, @"Transport write failed");
+  }
+  return YES;
 }
 
-- (void) writeByteDirect: (int8_t) n
+-(BOOL) writeVarint32:(UInt32)n error:(NSError *__autoreleasing *)error
 {
-  [mTransport write: (uint8_t *)&n offset: 0 length: 1];
-}
+  UInt8 i32buf[5] = {0};
+  UInt32 idx = 0;
 
-- (void)writeVarint32: (uint32_t) n
-{
-  uint8_t i32buf[5] = {0};
-  uint32_t idx = 0;
-  
   while (true) {
     if ((n & ~0x7F) == 0) {
-      i32buf[idx++] = (uint8_t)n;
+      i32buf[idx++] = (UInt8)n;
       break;
-    } else {
-      i32buf[idx++] = (uint8_t)((n & 0x7F) | 0x80);
+    }
+    else {
+      i32buf[idx++] = (UInt8)((n & 0x7F) | 0x80);
       n >>= 7;
     }
   }
-  
-  [mTransport write: i32buf offset: 0 length: idx];
+
+  if (![_transport write:i32buf offset:0 length:idx error:error]) {
+    PROTOCOL_TRANSPORT_ERROR(NO, error, @"Transport write failed");
+  }
+
+  return YES;
 }
 
-- (void) writeMessageBeginWithName: (NSString *) name
-                              type: (int) messageType
-                        sequenceID: (int) sequenceID
+-(BOOL) writeMessageBeginWithName:(NSString *)name
+                             type:(SInt32)messageType
+                       sequenceID:(SInt32)sequenceID
+                            error:(NSError *__autoreleasing *)error
 {
-  [self writeByteDirect: COMPACT_PROTOCOL_ID];
-  [self writeByteDirect: (uint8_t)((COMPACT_VERSION & COMPACT_VERSION_MASK) |
-                                   ((((uint32_t)messageType) << COMPACT_TYPE_SHIFT_AMOUNT) & COMPACT_TYPE_MASK))];
-  [self writeVarint32: (uint32_t)sequenceID];
-  [self writeString: name];
+  if (![self writeByteDirect:COMPACT_PROTOCOL_ID error:error]) {
+    return NO;
+  }
+  if (![self writeByteDirect:(UInt8)((COMPACT_VERSION & COMPACT_VERSION_MASK) |
+                                     ((((UInt32)messageType) << COMPACT_TYPE_SHIFT_AMOUNT) & COMPACT_TYPE_MASK)) error:error])
+  {
+    return NO;
+  }
+  if (![self writeVarint32:(UInt32)sequenceID error:error]) {
+    return NO;
+  }
+  if (![self writeString:name error:error]) {
+    return NO;
+  }
+
+  _currentMessageName = name;
+
+  return YES;
 }
 
-- (void) writeStructBeginWithName: (NSString *) name
+-(BOOL) writeStructBeginWithName:(NSString *)name error:(NSError *__autoreleasing *)error
 {
-  [lastField addObject: [NSNumber numberWithShort: lastFieldId]];
-  lastFieldId = 0;
+  [_lastField addObject:@(_lastFieldId)];
+  _lastFieldId = 0;
+  return YES;
 }
 
-- (void) writeStructEnd
+-(BOOL) writeStructEnd:(NSError *__autoreleasing *)error
 {
-  lastFieldId = [[lastField lastObject] shortValue];
-  [lastField removeLastObject];
+  _lastFieldId = [_lastField.lastObject shortValue];
+  [_lastField removeLastObject];
+  return YES;
 }
 
-- (void) writeFieldBeginWithName: (NSString *) name
-                            type: (int) fieldType
-                         fieldID: (int) fieldID
+-(BOOL) writeFieldBeginWithName:(NSString *)name
+                           type:(SInt32)fieldType
+                        fieldID:(SInt32)fieldID
+                          error:(NSError *__autoreleasing *)error
 {
-  if (fieldType == TType_BOOL) {
-    boolFieldName = [name copy];
-    boolFieldType = [[NSNumber numberWithInt: fieldType] retain_stub];
-    boolFieldId = [[NSNumber numberWithInt: fieldID] retain_stub];
-  } else {
-    [self writeFieldBeginInternalWithName: name
-                                     type: fieldType
-                                  fieldID: fieldID
-                             typeOverride: 0xFF];
+  if (fieldType == TTypeBOOL) {
+    _boolFieldName = [name copy];
+    _boolFieldType = @(fieldType);
+    _boolFieldId = @(fieldID);
+    return YES;
+  }
+  else {
+    return [self writeFieldBeginInternalWithName:name
+                                            type:fieldType
+                                         fieldID:fieldID
+                                    typeOverride:0xFF
+                                           error:error];
   }
 }
 
-- (void) writeFieldBeginInternalWithName: (NSString *) name
-                                    type: (int) fieldType
-                                 fieldID: (int) fieldID
-                            typeOverride: (uint8_t) typeOverride
+-(BOOL) writeFieldBeginInternalWithName:(NSString *)name
+                                   type:(SInt32)fieldType
+                                fieldID:(SInt32)fieldID
+                           typeOverride:(UInt8)typeOverride
+                                  error:(NSError *__autoreleasing *)error
 {
-  uint8_t typeToWrite = typeOverride == 0xFF ? [self compactTypeForTType: fieldType] : typeOverride;
-  
+  UInt8 typeToWrite = typeOverride == 0xFF ? [self compactTypeForTType:fieldType] : typeOverride;
+
   // check if we can use delta encoding for the field id
-  if (fieldID > lastFieldId && fieldID - lastFieldId <= 15) {
+  if (fieldID > _lastFieldId && fieldID - _lastFieldId <= 15) {
     // Write them together
-    [self writeByteDirect: (fieldID - lastFieldId) << 4 | typeToWrite];
-  } else {
+    if (![self writeByteDirect:(fieldID - _lastFieldId) << 4 | typeToWrite error:error]) {
+      return NO;
+    }
+  }
+  else {
     // Write them separate
-    [self writeByteDirect: typeToWrite];
-    [self writeI16: fieldID];
+    if (![self writeByteDirect:typeToWrite error:error]) {
+      return NO;
+    }
+    if (![self writeI16:fieldID error:error]) {
+      return NO;
+    }
   }
-  
-  lastFieldId = fieldID;
+
+  _lastFieldId = fieldID;
+
+  return YES;
 }
 
-- (void) writeFieldStop
+-(BOOL) writeFieldStop:(NSError *__autoreleasing *)error
 {
-  [self writeByteDirect: TCType_STOP];
+  return [self writeByteDirect:TCType_STOP error:error];
 }
 
-- (void) writeMapBeginWithKeyType: (int) keyType
-                        valueType: (int) valueType
-                             size: (int) size
+-(BOOL) writeMapBeginWithKeyType:(SInt32)keyType
+                       valueType:(SInt32)valueType
+                            size:(SInt32)size
+                           error:(NSError *__autoreleasing *)error
 {
   if (size == 0) {
-    [self writeByteDirect: 0];
-  } else {
-    [self writeVarint32: (uint32_t)size];
-    [self writeByteDirect: [self compactTypeForTType: keyType] << 4 | [self compactTypeForTType: valueType]];
+    if (![self writeByteDirect:0 error:error]) {
+      return NO;
+    }
   }
+  else {
+    if (![self writeVarint32:(UInt32)size error:error]) {
+      return NO;
+    }
+    if (![self writeByteDirect:[self compactTypeForTType:keyType] << 4 | [self compactTypeForTType:valueType] error:error]) {
+      return NO;
+    }
+  }
+  return YES;
 }
 
-- (void) writeListBeginWithElementType: (int) elementType
-                                  size: (int) size
+-(BOOL) writeListBeginWithElementType:(SInt32)elementType
+                                 size:(SInt32)size
+                                error:(NSError *__autoreleasing *)error
 {
-  [self writeCollectionBeginWithElementType: elementType size: size];
+  return [self writeCollectionBeginWithElementType:elementType size:size error:error];
 }
 
-- (void) writeSetBeginWithElementType: (int) elementType
-                                 size: (int) size
+-(BOOL) writeSetBeginWithElementType:(SInt32)elementType
+                                size:(SInt32)size
+                               error:(NSError *__autoreleasing *)error
 {
-  [self writeCollectionBeginWithElementType: elementType size: size];
+  return [self writeCollectionBeginWithElementType:elementType size:size error:error];
 }
 
-- (void) writeBool: (BOOL) b
+-(BOOL) writeBool:(BOOL)b error:(NSError *__autoreleasing *)error
 {
-  if (boolFieldId != nil && boolFieldName != nil && boolFieldType != nil) {
+  BOOL result;
+  if (_boolFieldId != nil && _boolFieldName != nil && _boolFieldType != nil) {
     // we haven't written the field header yet
-    [self writeFieldBeginInternalWithName: boolFieldName
-                                     type: [boolFieldType intValue]
-                                  fieldID: [boolFieldId intValue]
-                             typeOverride: b ? TCType_BOOLEAN_TRUE : TCType_BOOLEAN_FALSE];
-    
-    [boolFieldId release_stub];
-    [boolFieldName release_stub];
-    [boolFieldType release_stub];
-    
-    boolFieldId = nil;
-    boolFieldName = nil;
-    boolFieldType = nil;
-  } else {
+    result = [self writeFieldBeginInternalWithName:_boolFieldName
+                                              type:_boolFieldType.intValue
+                                           fieldID:_boolFieldId.intValue
+                                      typeOverride:b ? TCType_BOOLEAN_TRUE : TCType_BOOLEAN_FALSE
+                                             error:error];
+    _boolFieldId = nil;
+    _boolFieldName = nil;
+    _boolFieldType = nil;
+  }
+  else {
     // we're not part of a field, so just Write the value.
-    [self writeByteDirect: b ? TCType_BOOLEAN_TRUE : TCType_BOOLEAN_FALSE];
+    result = [self writeByteDirect:b ? TCType_BOOLEAN_TRUE : TCType_BOOLEAN_FALSE error:error];
   }
+  return result;
 }
 
-- (void) writeByte: (uint8_t) value
+-(BOOL) writeByte:(UInt8)value error:(NSError *__autoreleasing *)error
 {
-  [self writeByteDirect: value];
+  return [self writeByteDirect:value error:error];
 }
 
-- (void) writeI16: (int16_t) value
+-(BOOL) writeI16:(SInt16)value error:(NSError *__autoreleasing *)error
 {
-  [self writeVarint32: [self i32ToZigZag: value]];
+  return [self writeVarint32:[self i32ToZigZag:value] error:error];
 }
 
-- (void) writeI32: (int32_t) value
+-(BOOL) writeI32:(SInt32)value error:(NSError *__autoreleasing *)error
 {
-  [self writeVarint32: [self i32ToZigZag: value]];
+  return [self writeVarint32:[self i32ToZigZag:value] error:error];
 }
 
-- (void) writeI64: (int64_t) value
+-(BOOL) writeI64:(SInt64)value error:(NSError *__autoreleasing *)error
 {
-  [self writeVarint64: [self i64ToZigZag: value]];
+  return [self writeVarint64:[self i64ToZigZag:value] error:error];
 }
 
-- (void) writeDouble: (double) value
+-(BOOL) writeDouble:(double)value error:(NSError *__autoreleasing *)error
 {
-  //Safe bit-casting double->uint64
-  
-  uint64_t bits = 0;
+  // Safe bit-casting double->uint64
+
+  UInt64 bits = 0;
   memcpy(&bits, &value, 8);
-  
+
   bits = OSSwapHostToLittleInt64(bits);
-  
-  [mTransport write: (uint8_t *)&bits offset: 0 length: 8];
+
+  if (![_transport write:(UInt8 *)&bits offset:0 length:8 error:error]) {
+    PROTOCOL_TRANSPORT_ERROR(NO, error, @"Transport write failed");
+  }
+
+  return YES;
 }
 
-- (void) writeString: (NSString *) value
+-(BOOL) writeString:(NSString *)value error:(NSError *__autoreleasing *)error
 {
-  [self writeBinary: [value dataUsingEncoding: NSUTF8StringEncoding]];
+  return [self writeBinary:[value dataUsingEncoding:NSUTF8StringEncoding] error:error];
 }
 
-- (void) writeBinary: (NSData *) data
+-(BOOL) writeBinary:(NSData *)data error:(NSError *__autoreleasing *)error
 {
-  [self writeVarint32: (uint32_t)data.length];
-  [mTransport write: data.bytes offset: 0 length: data.length];
+  if (![self writeVarint32:(UInt32)data.length error:error]) {
+    return NO;
+  }
+  if (![_transport write:data.bytes offset:0 length:(UInt32)data.length error:error]) {
+    PROTOCOL_TRANSPORT_ERROR(NO, error, @"Transport write failed");
+  }
+  return YES;
 }
 
-- (void) writeMessageEnd {}
-- (void) writeMapEnd {}
-- (void) writeListEnd {}
-- (void) writeSetEnd {}
-- (void) writeFieldEnd {}
+-(BOOL) writeMessageEnd:(NSError *__autoreleasing *)error
+{
+  _currentMessageName = nil;
+  return YES;
+}
 
-- (void) writeCollectionBeginWithElementType: (int) elementType
-                                        size: (int) size
+-(BOOL) writeMapEnd:(NSError *__autoreleasing *)error
 {
+  return YES;
+}
+
+-(BOOL) writeListEnd:(NSError *__autoreleasing *)error
+{
+  return YES;
+}
+
+-(BOOL) writeSetEnd:(NSError *__autoreleasing *)error
+{
+  return YES;
+}
+
+-(BOOL) writeFieldEnd:(NSError *__autoreleasing *)error
+{
+  return YES;
+}
+
+-(BOOL) writeCollectionBeginWithElementType:(SInt32)elementType
+                                       size:(SInt32)size
+                                      error:(NSError *__autoreleasing *)error
+{
+  UInt8 ctypeElement = [self compactTypeForTType:elementType];
+
   if (size <= 14) {
-    [self writeByteDirect: size << 4 | [self compactTypeForTType: elementType]];
-  } else {
-    [self writeByteDirect: 0xf0 | [self compactTypeForTType: elementType]];
-    [self writeVarint32: (uint32_t)size];
+    if (![self writeByteDirect:size << 4 | ctypeElement error:error]) {
+      return NO;
+    }
   }
+  else {
+    if (![self writeByteDirect:0xf0 | ctypeElement error:error]) {
+      return NO;
+    }
+    if (![self writeVarint32:(UInt32)size error:error]) {
+      return NO;
+    }
+  }
+  return YES;
 }
 
-- (void) writeVarint64: (uint64_t) n
+-(BOOL) writeVarint64:(UInt64)n error:(NSError *__autoreleasing *)error
 {
-  uint8_t varint64out[10] = {0};
+  UInt8 varint64out[10] = {0};
   int idx = 0;
-  
+
   while (true) {
     if ((n & ~0x7FL) == 0) {
-      varint64out[idx++] = (uint8_t)n;
+      varint64out[idx++] = (UInt8)n;
       break;
-    } else {
-      varint64out[idx++] = (uint8_t)((n & 0x7F) | 0x80);
+    }
+    else {
+      varint64out[idx++] = (UInt8)((n & 0x7F) | 0x80);
       n >>= 7;
     }
   }
-  
-  [mTransport write: varint64out offset: 0 length: idx];
+
+  if (![_transport write:varint64out offset:0 length:idx error:error]) {
+    PROTOCOL_TRANSPORT_ERROR(NO, error, @"Transport write failed");
+  }
+
+  return YES;
 }
 
-- (uint32_t) i32ToZigZag: (int32_t) n
+-(UInt32) i32ToZigZag:(SInt32)n
 {
   /*
-   ZigZag encoding maps signed integers to unsigned integers so that
-   numbers with a small absolute value (for instance, -1) have
-   a small varint encoded value too. It does this in a way that
-   "zig-zags" back and forth through the positive and negative integers,
-   so that -1 is encoded as 1, 1 is encoded as 2, -2 is encoded as 3, and so on
+     ZigZag encoding maps signed integers to unsigned integers so that
+     numbers with a small absolute value (for instance, -1) have
+     a small varint encoded value too. It does this in a way that
+     "zig-zags" back and forth through the positive and negative integers,
+     so that -1 is encoded as 1, 1 is encoded as 2, -2 is encoded as 3, and so
+         on
    */
-  return (uint32_t)(n << 1) ^ (uint32_t)(n >> 31);
+  return (UInt32)(n << 1) ^ (UInt32)(n >> 31);
 }
 
-- (uint64_t) i64ToZigZag: (int64_t) n
+-(UInt64) i64ToZigZag:(SInt64)n
 {
-  return (uint64_t)(n << 1) ^ (uint64_t)(n >> 63);
+  return (UInt64)(n << 1) ^ (UInt64)(n >> 63);
 }
 
-- (void) readMessageBeginReturningName: (NSString **) pname
-                                  type: (int *) ptype
-                            sequenceID: (int *) psequenceID
+-(BOOL) readMessageBeginReturningName:(NSString **)pname
+                                 type:(SInt32 *)ptype
+                           sequenceID:(SInt32 *)psequenceID
+                                error:(NSError *__autoreleasing *)error
 {
-  uint8_t protocolId = [self readByte];
+  UInt8 protocolId;
+  if (![self readByte:&protocolId error:error]) {
+    return NO;
+  }
+
   if (protocolId != COMPACT_PROTOCOL_ID) {
-    @throw [TProtocolException exceptionWithName: @"TProtocolException"
-                                          reason: [NSString stringWithFormat: @"Expected protocol id %X but got %X", COMPACT_PROTOCOL_ID, protocolId]];
+    if (error) {
+      *error = [NSError errorWithDomain:TProtocolErrorDomain
+                                   code:TProtocolErrorUnknown
+                               userInfo:@{TProtocolErrorExtendedErrorKey: @(TProtocolExtendedErrorMismatchedProtocol),
+                                          TProtocolErrorExpectedIdKey: @(COMPACT_PROTOCOL_ID)}];
+    }
+    return NO;
   }
-  
-  uint8_t versionAndType = [self readByte];
-  uint8_t version = versionAndType & COMPACT_VERSION_MASK;
+
+  UInt8 versionAndType;
+  if (![self readByte:&versionAndType error:error]) {
+    return NO;
+  }
+
+  UInt8 version = versionAndType & COMPACT_VERSION_MASK;
   if (version != COMPACT_VERSION) {
-    @throw [TProtocolException exceptionWithName: @"TProtocolException"
-                                          reason: [NSString stringWithFormat: @"Expected version %d but got %d", COMPACT_VERSION, version]];
+    if (error) {
+      *error = [NSError errorWithDomain:TProtocolErrorDomain
+                                   code:TProtocolErrorBadVersion
+                               userInfo:@{TProtocolErrorExpectedVersionKey: @(COMPACT_VERSION)}];
+    }
+    return NO;
   }
-  
+
   int type = (versionAndType >> COMPACT_TYPE_SHIFT_AMOUNT) & COMPACT_TYPE_BITS;
-  int sequenceID = (int)[self readVarint32];
-  NSString* name = [self readString];
-  
+  UInt32 sequenceID;
+  if (![self readVarint32:&sequenceID error:error]) {
+    return NO;
+  }
+  NSString *name;
+  if (![self readString:&name error:error]) {
+    return NO;
+  }
+
   if (ptype != NULL) {
     *ptype = type;
   }
@@ -371,59 +490,74 @@ enum {
   if (pname != NULL) {
     *pname = name;
   }
+  return YES;
 }
 
-- (void) readStructBeginReturningName: (NSString **) pname
+-(BOOL) readStructBeginReturningName:(NSString **)pname error:(NSError *__autoreleasing *)error
 {
-  [lastField addObject: [NSNumber numberWithShort: lastFieldId]];
-  lastFieldId = 0;
-  
+  [_lastField addObject:@(_lastFieldId)];
+  _lastFieldId = 0;
+
   if (pname != NULL) {
     *pname = @"";
   }
+
+  return YES;
 }
 
-- (void) readStructEnd
+-(BOOL) readStructEnd:(NSError *__autoreleasing *)error
 {
-  lastFieldId = [[lastField lastObject] shortValue];
-  [lastField removeLastObject];
+  _lastFieldId = [_lastField.lastObject shortValue];
+  [_lastField removeLastObject];
+  return YES;
 }
 
-- (void) readFieldBeginReturningName: (NSString **) pname
-                                type: (int *) pfieldType
-                             fieldID: (int *) pfieldID
+-(BOOL) readFieldBeginReturningName:(NSString **)pname
+                               type:(SInt32 *)pfieldType
+                            fieldID:(SInt32 *)pfieldID
+                              error:(NSError *__autoreleasing *)error
 {
-  uint8_t byte = [self readByte];
-  uint8_t type = byte & 0x0f;
-  
+  UInt8 byte;
+  if (![self readByte:&byte error:error]) {
+    return NO;
+  }
+
+  UInt8 type = byte & 0x0f;
+
   // if it's a stop, then we can return immediately, as the struct is over.
   if (type == TCType_STOP) {
     if (pname != NULL) {
       *pname = @"";
     }
     if (pfieldType != NULL) {
-      *pfieldType = TType_STOP;
+      *pfieldType = TTypeSTOP;
     }
     if (pfieldID != NULL) {
       *pfieldID = 0;
     }
-    return;
+    return YES;
   }
-  
+
   short fieldId = 0;
-  
+
   // mask off the 4 MSB of the type header. it could contain a field id delta.
   short modifier = (byte & 0xf0) >> 4;
   if (modifier == 0) {
     // not a delta. look ahead for the zigzag varint field id.
-    fieldId = [self readI16];
-  } else {
+    if (![self readI16:&fieldId error:error]) {
+      return NO;
+    }
+  }
+  else {
     // has a delta. add the delta to the last Read field id.
-    fieldId = lastFieldId + modifier;
+    fieldId = _lastFieldId + modifier;
   }
-  
-  int fieldType = [self ttypeForCompactType: type];
-  
+
+  UInt8 fieldType;
+  if (![self ttype:&fieldType forCompactType:type error:error]) {
+    return NO;
+  }
+
   if (pname != NULL) {
     *pname = @"";
   }
@@ -433,31 +567,47 @@ enum {
   if (pfieldID != NULL) {
     *pfieldID = fieldId;
   }
-  
+
   // if this happens to be a boolean field, the value is encoded in the type
   if (type == TCType_BOOLEAN_TRUE ||
-      type == TCType_BOOLEAN_FALSE) {
+      type == TCType_BOOLEAN_FALSE)
+  {
     // save the boolean value in a special instance variable.
-    booleanValue = [[NSNumber numberWithBool: type == TCType_BOOLEAN_TRUE] retain_stub];
+    _booleanValue = [NSNumber numberWithBool:type == TCType_BOOLEAN_TRUE];
   }
-  
+
   // push the new field onto the field stack so we can keep the deltas going.
-  lastFieldId = fieldId;
+  _lastFieldId = fieldId;
+
+  return YES;
 }
 
-- (void) readMapBeginReturningKeyType: (int *) pkeyType
-                            valueType: (int *) pvalueType
-                                 size: (int *) psize
+-(BOOL) readMapBeginReturningKeyType:(SInt32 *)pkeyType
+                           valueType:(SInt32 *)pvalueType
+                                size:(SInt32 *)psize
+                               error:(NSError *__autoreleasing *)error
 {
-  uint8_t keyAndValueType = 0;
-  int size = (int)[self readVarint32];
+  UInt8 keyAndValueType = 0;
+  UInt32 size;
+  if (![self readVarint32:&size error:error]) {
+    return NO;
+  }
   if (size != 0) {
-    keyAndValueType = [self readByte];
+    if (![self readByte:&keyAndValueType error:error]) {
+      return NO;
+    }
+  }
+
+  UInt8 keyType;
+  if (![self ttype:&keyType forCompactType:keyAndValueType >> 4 error:error]) {
+    return NO;
   }
-  
-  int keyType = [self ttypeForCompactType: keyAndValueType >> 4];
-  int valueType = [self ttypeForCompactType: keyAndValueType & 0xf];
-  
+
+  UInt8 valueType;
+  if (![self ttype:&valueType forCompactType:keyAndValueType & 0xf error:error]) {
+    return NO;
+  }
+
   if (pkeyType != NULL) {
     *pkeyType = keyType;
   }
@@ -467,220 +617,366 @@ enum {
   if (psize != NULL) {
     *psize = size;
   }
+
+  return YES;
 }
 
-- (void) readListBeginReturningElementType: (int *) pelementType
-                                      size: (int *) psize
+-(BOOL) readListBeginReturningElementType:(SInt32 *)pelementType
+                                     size:(SInt32 *)psize
+                                    error:(NSError *__autoreleasing *)error
 {
-  uint8_t size_and_type = [self readByte];
-  int size = (size_and_type >> 4) & 0x0f;
+  UInt8 sizeAndType;
+  if (![self readByte:&sizeAndType error:error]) {
+    return NO;
+  }
+
+  UInt32 size = (sizeAndType >> 4) & 0x0f;
   if (size == 15) {
-    size = (int)[self readVarint32];
+    if (![self readVarint32:&size error:error]) {
+      return NO;
+    }
   }
-  
-  int elementType = [self ttypeForCompactType: size_and_type & 0x0f];
-  
+
+  UInt8 elementType;
+  if (![self ttype:&elementType forCompactType:sizeAndType & 0x0f error:error]) {
+    return NO;
+  }
+
   if (pelementType != NULL) {
     *pelementType = elementType;
   }
   if (psize != NULL) {
     *psize = size;
   }
+
+  return YES;
 }
 
-- (void) readSetBeginReturningElementType: (int *) pelementType
-                                     size: (int *) psize
+-(BOOL) readSetBeginReturningElementType:(SInt32 *)pelementType
+                                    size:(SInt32 *)psize
+                                   error:(NSError *__autoreleasing *)error
 {
-  [self readListBeginReturningElementType: pelementType size: psize];
+  return [self readListBeginReturningElementType:pelementType size:psize error:error];
 }
 
-- (BOOL) readBool
+-(BOOL) readBool:(BOOL *)value error:(NSError *__autoreleasing *)error
 {
-  if (booleanValue != nil) {
-    BOOL result = [booleanValue boolValue];
-    [booleanValue release_stub];
-    booleanValue = nil;
-    return result;
-  } else {
-    return [self readByte] == TCType_BOOLEAN_TRUE;
+  if (_booleanValue != nil) {
+
+    BOOL result = _booleanValue.boolValue;
+    _booleanValue = nil;
+
+    *value = result;
+  }
+  else {
+
+    UInt8 result;
+    if (![self readByte:&result error:error]) {
+      return NO;
+    }
+
+    *value = result == TCType_BOOLEAN_TRUE;
   }
+
+  return YES;
 }
 
-- (uint8_t) readByte
+-(BOOL) readByte:(UInt8 *)value error:(NSError *__autoreleasing *)error
 {
-  uint8_t buf = 0;
-  [mTransport readAll: &buf offset: 0 length: 1];
-  return buf;
+  if (![_transport readAll:value offset:0 length:1 error:error]) {
+    PROTOCOL_TRANSPORT_ERROR(NO, error, @"Transport read failed");
+  }
+  return YES;
 }
 
-- (int16_t) readI16
+-(BOOL) readI16:(SInt16 *)value error:(NSError *__autoreleasing *)error
 {
-  return (int16_t)[self zigZagToi32: [self readVarint32]];
+  UInt32 v;
+  if (![self readVarint32:&v error:error]) {
+    return NO;
+  }
+
+  if (value) {
+    *value = (SInt16)[self zigZagToi32:v];
+  }
+
+  return YES;
 }
 
-- (int32_t) readI32
+-(BOOL) readI32:(SInt32 *)value error:(NSError *__autoreleasing *)error
 {
-  return [self zigZagToi32: [self readVarint32]];
+  UInt32 v;
+  if (![self readVarint32:&v error:error]) {
+    return NO;
+  }
+
+  if (value) {
+    *value = [self zigZagToi32:v];
+  }
+
+  return YES;
 }
 
-- (int64_t) readI64
+-(BOOL) readI64:(SInt64 *)value error:(NSError *__autoreleasing *)error
 {
-  return [self zigZagToi64: [self readVarint64]];
+  UInt64 v;
+  if (![self readVarint64:&v error:error]) {
+    return NO;
+  }
+
+  if (value) {
+    *value = [self zigZagToi64:v];
+  }
+
+  return YES;
 }
 
-- (double) readDouble
+-(BOOL) readDouble:(double *)value error:(NSError *__autoreleasing *)error
 {
-  uint64_t bits = 0;
-  [mTransport readAll: (uint8_t *)&bits offset: 0 length: 8];
+  UInt64 bits;
+  if (![_transport readAll:(UInt8 *)&bits offset:0 length:8 error:error]) {
+    PROTOCOL_TRANSPORT_ERROR(NO, error, @"Transport read failed");
+  }
+
   bits = OSSwapLittleToHostInt64(bits);
-  
-  double result = 0;
-  memcpy(&result, &bits, 8);
-  
-  return result;
+
+  if (value) {
+    memcpy(value, &bits, sizeof(bits));
+  }
+
+  return YES;
 }
 
-- (NSString *) readString
+-(BOOL) readString:(NSString *__autoreleasing *)value error:(NSError *__autoreleasing *)error
 {
-  int length = (int)[self readVarint32];
-  if (length == 0) {
-    return @"";
+  UInt32 length;
+  if (![self readVarint32:&length error:error]) {
+    return NO;
+  }
+
+  NSString *result;
+
+  if (length != 0) {
+
+    NSData *data;
+    if (![self readBinaryOfLength:length data:&data error:error]) {
+      return NO;
+    }
+
+    result = [[NSString alloc] initWithData:data
+                                   encoding:NSUTF8StringEncoding];
+  }
+  else {
+    result = @"";
   }
-  
-  return [[[NSString alloc] initWithData: [self readBinary: length]
-                                encoding: NSUTF8StringEncoding] autorelease_stub];
+
+  if (value) {
+    *value = result;
+  }
+
+  return YES;
 }
 
-- (NSData *) readBinary
+-(BOOL) readBinary:(NSData *__autoreleasing *)value error:(NSError *__autoreleasing *)error
 {
-  return [self readBinary: (int)[self readVarint32]];
+  UInt32 length;
+  if (![self readVarint32:&length error:error]) {
+    return NO;
+  }
+
+  return [self readBinaryOfLength:length data:value error:error];
 }
 
-- (NSData *) readBinary: (int) length
+-(BOOL) readBinaryOfLength:(UInt32)length data:(NSData *__autoreleasing *)value error:(NSError *__autoreleasing *)error
 {
-  if (length == 0) {
-    return [NSData data];
+  NSData *result;
+
+  if (length != 0) {
+
+    NSMutableData *buf = [NSMutableData dataWithLength:length];
+    if (![_transport readAll:buf.mutableBytes offset:0 length:length error:error]) {
+      PROTOCOL_TRANSPORT_ERROR(NO, error, @"Transport read failed");
+    }
+
+    result = buf;
+  }
+  else {
+
+    result = [NSData data];
+
+  }
+
+  if (value) {
+    *value = result;
   }
-  
-  NSMutableData* buf = [NSMutableData dataWithLength: length];
-  [mTransport readAll: buf.mutableBytes offset: 0 length: length];
-  return buf;
+
+  return YES;
 }
 
-- (void) readMessageEnd {}
-- (void) readFieldEnd {}
-- (void) readMapEnd {}
-- (void) readListEnd {}
-- (void) readSetEnd {}
+-(BOOL) readMessageEnd:(NSError *__autoreleasing *)error
+{
+  return YES;
+}
+-(BOOL) readFieldEnd:(NSError *__autoreleasing *)error
+{
+  return YES;
+}
+-(BOOL) readMapEnd:(NSError *__autoreleasing *)error
+{
+  return YES;
+}
+-(BOOL) readListEnd:(NSError *__autoreleasing *)error
+{
+  return YES;
+}
+-(BOOL) readSetEnd:(NSError *__autoreleasing *)error
+{
+  return YES;
+}
 
-- (uint32_t) readVarint32
+-(BOOL) readVarint32:(UInt32 *)value error:(NSError *__autoreleasing *)error
 {
-  uint32_t result = 0;
+  UInt32 result = 0;
   int shift = 0;
-  
+
   while (true) {
-    uint8_t byte = [self readByte];
-    result |= (uint32_t)(byte & 0x7f) << shift;
+
+    UInt8 byte;
+    if (![self readByte:&byte error:error]) {
+      return NO;
+    }
+
+    result |= (UInt32)(byte & 0x7f) << shift;
     if (!(byte & 0x80)) {
       break;
     }
-    
+
     shift += 7;
   }
-  return result;
+
+  if (value) {
+    *value = result;
+  }
+
+  return YES;
 }
 
-- (uint64_t) readVarint64
+-(BOOL) readVarint64:(UInt64 *)value error:(NSError *__autoreleasing *)error
 {
   int shift = 0;
-  uint64_t result = 0;
-  
+  UInt64 result = 0;
+
   while (true) {
-    uint8_t byte = [self readByte];
-    result |= (uint64_t)(byte & 0x7f) << shift;
+
+    UInt8 byte;
+    if (![self readByte:&byte error:error]) {
+      return NO;
+    }
+
+    result |= (UInt64)(byte & 0x7f) << shift;
     if (!(byte & 0x80)) {
       break;
     }
-    
+
     shift += 7;
   }
-  
-  return result;
+
+  if (value) {
+    *value = result;
+  }
+
+  return YES;
+}
+
+-(SInt32) zigZagToi32:(UInt32)n
+{
+  return (SInt32)(n >> 1) ^ (-(SInt32)(n & 1));
+}
+
+-(SInt64) zigZagToi64:(UInt64)n
+{
+  return (SInt64)(n >> 1) ^ (-(SInt64)(n & 1));
 }
 
-- (int32_t) zigZagToi32: (uint32_t) n
-{
-  return (int32_t)(n >> 1) ^ (-(int32_t)(n & 1));
-}
-
-- (int64_t) zigZagToi64: (uint64_t) n
-{
-  return (int64_t)(n >> 1) ^ (-(int64_t)(n & 1));
-}
-
-- (uint8_t) ttypeForCompactType: (uint8_t) type
-{
-  switch (type & 0x0f) {
-    case TCType_STOP:
-      return TType_STOP;
-      
-    case TCType_BOOLEAN_FALSE:
-    case TCType_BOOLEAN_TRUE:
-      return TType_BOOL;
-      
-    case TCType_BYTE:
-      return TType_BYTE;
-      
-    case TCType_I16:
-      return TType_I16;
-      
-    case TCType_I32:
-      return TType_I32;
-      
-    case TCType_I64:
-      return TType_I64;
-      
-    case TCType_DOUBLE:
-      return TType_DOUBLE;
-      
-    case TCType_BINARY:
-      return TType_STRING;
-      
-    case TCType_LIST:
-      return TType_LIST;
-      
-    case TCType_SET:
-      return TType_SET;
-      
-    case TCType_MAP:
-      return TType_MAP;
-      
-    case TCType_STRUCT:
-      return TType_STRUCT;
-      
-    default:
-      @throw [TProtocolException exceptionWithName: @"TProtocolException"
-                                            reason: [NSString stringWithFormat: @"Don't know what type: %d", (uint8_t)(type & 0x0F)]];
-  }
-}
-
-- (uint8_t) compactTypeForTType: (uint8_t) ttype
-{
-  static uint8_t ttypeToCompactType[] = {
-    [TType_STOP] = TCType_STOP,
-    [TType_BOOL] = TCType_BOOLEAN_FALSE,
-    [TType_BYTE] = TCType_BYTE,
-    [TType_DOUBLE] = TCType_DOUBLE,
-    [TType_I16] = TCType_I16,
-    [TType_I32] = TCType_I32,
-    [TType_I64] = TCType_I64,
-    [TType_STRING] = TCType_BINARY,
-    [TType_STRUCT] = TCType_STRUCT,
-    [TType_MAP] = TCType_MAP,
-    [TType_SET] = TCType_SET,
-    [TType_LIST] = TCType_LIST
+-(BOOL) ttype:(UInt8 *)ttype forCompactType:(UInt8)ctype error:(NSError *__autoreleasing *)error
+{
+  switch (ctype & 0x0f) {
+  case TCType_STOP:
+    *ttype = TTypeSTOP;
+    return YES;
+
+  case TCType_BOOLEAN_FALSE:
+  case TCType_BOOLEAN_TRUE:
+    *ttype = TTypeBOOL;
+    return YES;
+
+  case TCType_BYTE:
+    *ttype = TTypeBYTE;
+    return YES;
+
+  case TCType_I16:
+    *ttype = TTypeI16;
+    return YES;
+
+  case TCType_I32:
+    *ttype = TTypeI32;
+    return YES;
+
+  case TCType_I64:
+    *ttype = TTypeI64;
+    return YES;
+
+  case TCType_DOUBLE:
+    *ttype = TTypeDOUBLE;
+    return YES;
+
+  case TCType_BINARY:
+    *ttype = TTypeSTRING;
+    return YES;
+
+  case TCType_LIST:
+    *ttype = TTypeLIST;
+    return YES;
+
+  case TCType_SET:
+    *ttype = TTypeSET;
+    return YES;
+
+  case TCType_MAP:
+    *ttype = TTypeMAP;
+    return YES;
+
+  case TCType_STRUCT:
+    *ttype = TTypeSTRUCT;
+    return YES;
+
+  default:
+    if (error) {
+      *error = [NSError errorWithDomain:TProtocolErrorDomain
+                                   code:TProtocolErrorUnknown
+                               userInfo:@{TProtocolErrorTypeKey: @((UInt8)(ctype & 0x0F))}];
+    }
+    return NO;
+  }
+}
+
+-(UInt8) compactTypeForTType:(UInt8)ttype
+{
+  static UInt8 ttypeToCompactType[] = {
+    [TTypeSTOP] = TCType_STOP,
+    [TTypeBOOL] = TCType_BOOLEAN_FALSE,
+    [TTypeBYTE] = TCType_BYTE,
+    [TTypeDOUBLE] = TCType_DOUBLE,
+    [TTypeI16] = TCType_I16,
+    [TTypeI32] = TCType_I32,
+    [TTypeI64] = TCType_I64,
+    [TTypeSTRING] = TCType_BINARY,
+    [TTypeSTRUCT] = TCType_STRUCT,
+    [TTypeMAP] = TCType_MAP,
+    [TTypeSET] = TCType_SET,
+    [TTypeLIST] = TCType_LIST
   };
-  
+
   return ttypeToCompactType[ttype];
 }
 

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/protocol/TMultiplexedProtocol.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/protocol/TMultiplexedProtocol.h b/lib/cocoa/src/protocol/TMultiplexedProtocol.h
index f298459..b8ce361 100644
--- a/lib/cocoa/src/protocol/TMultiplexedProtocol.h
+++ b/lib/cocoa/src/protocol/TMultiplexedProtocol.h
@@ -21,13 +21,18 @@
 
 #import "TProtocolDecorator.h"
 
-FOUNDATION_EXPORT NSString *const MULTIPLEXED_SERVICE_SEPERATOR;
+NS_ASSUME_NONNULL_BEGIN
 
-@interface TMultiplexedProtocol : TProtocolDecorator {
-    NSString * mServiceName;
-}
 
-- (id) initWithProtocol: (id <TProtocol>) protocol
-            serviceName: (NSString *) name;
+extern NSString *TMultiplexedProtocolSeperator;
+
+
+@interface TMultiplexedProtocol : TProtocolDecorator
+
+-(id) initWithProtocol:(id <TProtocol>)protocol
+           serviceName:(NSString *)name;
 
 @end
+
+
+NS_ASSUME_NONNULL_END
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/protocol/TMultiplexedProtocol.m
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/protocol/TMultiplexedProtocol.m b/lib/cocoa/src/protocol/TMultiplexedProtocol.m
index 49095e3..5838c57 100644
--- a/lib/cocoa/src/protocol/TMultiplexedProtocol.m
+++ b/lib/cocoa/src/protocol/TMultiplexedProtocol.m
@@ -20,48 +20,47 @@
 #import "TMultiplexedProtocol.h"
 
 #import "TProtocol.h"
-#import "TObjective-C.h"
 
-NSString *const MULTIPLEXED_SERVICE_SEPERATOR = @":";
+NSString *TMultiplexedProtocolSeperator = @":";
 
-@implementation TMultiplexedProtocol
 
-- (id) initWithProtocol: (id <TProtocol>) protocol
-            serviceName: (NSString *) name
-{
-    self = [super initWithProtocol:protocol];
+@interface TMultiplexedProtocol ()
 
-    if (self) {
-        mServiceName = [name retain_stub];
-    }
-    return self;
-}
+@property(strong, nonatomic) NSString *serviceName;
+
+@end
 
-- (void) writeMessageBeginWithName: (NSString *) name
-                              type: (int) messageType
-                        sequenceID: (int) sequenceID
+
+@implementation TMultiplexedProtocol
+
+-(id) initWithProtocol:(id <TProtocol>)protocol
+           serviceName:(NSString *)name
 {
-    switch (messageType) {
-        case TMessageType_CALL:
-        case TMessageType_ONEWAY:
-            {
-                NSMutableString * serviceFunction = [[NSMutableString alloc] initWithString:mServiceName];
-                [serviceFunction appendString:MULTIPLEXED_SERVICE_SEPERATOR];
-                [serviceFunction appendString:name];
-                [super writeMessageBeginWithName:serviceFunction type:messageType sequenceID:sequenceID];
-                [serviceFunction release_stub];
-            }
-            break;
-        default:
-            [super writeMessageBeginWithName:name type:messageType sequenceID:sequenceID];
-            break;
-    }
+  self = [super initWithProtocol:protocol];
+  if (self) {
+    _serviceName = name;
+  }
+  return self;
 }
 
-- (void) dealloc
+-(BOOL) writeMessageBeginWithName:(NSString *)name
+                             type:(SInt32)messageType
+                       sequenceID:(SInt32)sequenceID
+                            error:(NSError *__autoreleasing *)error
 {
-    [mServiceName release_stub];
-    [super dealloc_stub];
+  switch (messageType) {
+  case TMessageTypeCALL:
+  case TMessageTypeONEWAY: {
+    NSMutableString *serviceFunction = [[NSMutableString alloc] initWithString:_serviceName];
+    [serviceFunction appendString:TMultiplexedProtocolSeperator];
+    [serviceFunction appendString:name];
+    return [super writeMessageBeginWithName:serviceFunction type:messageType sequenceID:sequenceID error:error];
+  }
+  break;
+
+  default:
+    return [super writeMessageBeginWithName:name type:messageType sequenceID:sequenceID error:error];
+  }
 }
 
 @end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/protocol/TProtocol.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/protocol/TProtocol.h b/lib/cocoa/src/protocol/TProtocol.h
index 281239d..841059f 100644
--- a/lib/cocoa/src/protocol/TProtocol.h
+++ b/lib/cocoa/src/protocol/TProtocol.h
@@ -22,127 +22,143 @@
 #import "TTransport.h"
 
 
-enum {
-  TMessageType_CALL = 1,
-  TMessageType_REPLY = 2,
-  TMessageType_EXCEPTION = 3,
-  TMessageType_ONEWAY = 4
+NS_ASSUME_NONNULL_BEGIN
+
+
+typedef NS_ENUM (int, TMessageType) {
+  TMessageTypeCALL = 1,
+  TMessageTypeREPLY = 2,
+  TMessageTypeEXCEPTION = 3,
+  TMessageTypeONEWAY = 4
 };
 
-enum {
-  TType_STOP   = 0,
-  TType_VOID   = 1,
-  TType_BOOL   = 2,
-  TType_BYTE   = 3,
-  TType_DOUBLE = 4,
-  TType_I16    = 6,
-  TType_I32    = 8,
-  TType_I64    = 10,
-  TType_STRING = 11,
-  TType_STRUCT = 12,
-  TType_MAP    = 13,
-  TType_SET    = 14,
-  TType_LIST   = 15
+typedef NS_ENUM (int, TType) {
+  TTypeSTOP   = 0,
+  TTypeVOID   = 1,
+  TTypeBOOL   = 2,
+  TTypeBYTE   = 3,
+  TTypeDOUBLE = 4,
+  TTypeI16    = 6,
+  TTypeI32    = 8,
+  TTypeI64    = 10,
+  TTypeSTRING = 11,
+  TTypeSTRUCT = 12,
+  TTypeMAP    = 13,
+  TTypeSET    = 14,
+  TTypeLIST   = 15
 };
 
 
 @protocol TProtocol <NSObject>
 
-- (id <TTransport>) transport;
+-(id <TTransport>) transport;
 
-- (void) readMessageBeginReturningName: (NSString **) name
-                                  type: (int *) type
-                            sequenceID: (int *) sequenceID;
-- (void) readMessageEnd;
+-(BOOL) readMessageBeginReturningName:(NSString *__nullable __autoreleasing *__nullable)name
+                                 type:(nullable SInt32 *)type
+                           sequenceID:(nullable SInt32 *)sequenceID
+                                error:(NSError *__autoreleasing *)error;
+-(BOOL) readMessageEnd:(NSError *__autoreleasing *)error;
 
-- (void) readStructBeginReturningName: (NSString **) name;
-- (void) readStructEnd;
+-(BOOL) readStructBeginReturningName:(NSString *__nullable __autoreleasing *__nullable)name
+                               error:(NSError *__autoreleasing *)error;
+-(BOOL) readStructEnd:(NSError *__autoreleasing *)error;
 
-- (void) readFieldBeginReturningName: (NSString **) name
-                                type: (int *) fieldType
-                             fieldID: (int *) fieldID;
-- (void) readFieldEnd;
+-(BOOL) readFieldBeginReturningName:(NSString *__nullable __autoreleasing *__nullable)name
+                               type:(SInt32 *)fieldType
+                            fieldID:(nullable SInt32 *)fieldID
+                              error:(NSError *__autoreleasing *)error;
+-(BOOL) readFieldEnd:(NSError *__autoreleasing *)error;
 
-- (NSString *) readString;
+-(BOOL) readString:(NSString *__nonnull __autoreleasing *__nonnull)value error:(NSError **)error;
 
-- (BOOL) readBool;
+-(BOOL) readBool:(BOOL *)value error:(NSError *__autoreleasing *)error;
 
-- (unsigned char) readByte;
+-(BOOL) readByte:(UInt8 *)value error:(NSError *__autoreleasing *)error;
 
-- (short) readI16;
+-(BOOL) readI16:(SInt16 *)value error:(NSError *__autoreleasing *)error;
 
-- (int32_t) readI32;
+-(BOOL) readI32:(SInt32 *)value error:(NSError *__autoreleasing *)error;
 
-- (int64_t) readI64;
+-(BOOL) readI64:(SInt64 *)value error:(NSError *__autoreleasing *)error;
 
-- (double) readDouble;
+-(BOOL) readDouble:(double *)value error:(NSError *__autoreleasing *)error;
 
-- (NSData *) readBinary;
+-(BOOL) readBinary:(NSData *__nonnull __autoreleasing *__nonnull)value error:(NSError **)error;
 
-- (void) readMapBeginReturningKeyType: (int *) keyType
-                            valueType: (int *) valueType
-                                 size: (int *) size;
-- (void) readMapEnd;
+-(BOOL) readMapBeginReturningKeyType:(nullable SInt32 *)keyType
+                           valueType:(nullable SInt32 *)valueType
+                                size:(SInt32 *)size
+                               error:(NSError *__autoreleasing *)error;
+-(BOOL) readMapEnd:(NSError *__autoreleasing *)error;
 
 
-- (void) readSetBeginReturningElementType: (int *) elementType
-                                     size: (int *) size;
-- (void) readSetEnd;
+-(BOOL) readSetBeginReturningElementType:(nullable SInt32 *)elementType
+                                    size:(SInt32 *)size
+                                   error:(NSError *__autoreleasing *)error;
+-(BOOL) readSetEnd:(NSError *__autoreleasing *)error;
 
 
-- (void) readListBeginReturningElementType: (int *) elementType
-                                      size: (int *) size;
-- (void) readListEnd;
+-(BOOL) readListBeginReturningElementType:(nullable SInt32 *)elementType
+                                     size:(SInt32 *)size
+                                    error:(NSError *__autoreleasing *)error;
+-(BOOL) readListEnd:(NSError *__autoreleasing *)error;
 
 
-- (void) writeMessageBeginWithName: (NSString *) name
-                              type: (int) messageType
-                        sequenceID: (int) sequenceID;
-- (void) writeMessageEnd;
+-(BOOL) writeMessageBeginWithName:(NSString *)name
+                             type:(SInt32)messageType
+                       sequenceID:(SInt32)sequenceID
+                            error:(NSError *__autoreleasing *)error;
+-(BOOL) writeMessageEnd:(NSError *__autoreleasing *)error;
 
-- (void) writeStructBeginWithName: (NSString *) name;
-- (void) writeStructEnd;
+-(BOOL) writeStructBeginWithName:(NSString *)name error:(NSError **)error;
+-(BOOL) writeStructEnd:(NSError *__autoreleasing *)error;
 
-- (void) writeFieldBeginWithName: (NSString *) name
-                            type: (int) fieldType
-                         fieldID: (int) fieldID;
+-(BOOL) writeFieldBeginWithName:(NSString *)name
+                           type:(SInt32)fieldType
+                        fieldID:(SInt32)fieldID
+                          error:(NSError *__autoreleasing *)error;
 
-- (void) writeI32: (int32_t) value;
+-(BOOL) writeI32:(SInt32)value error:(NSError *__autoreleasing *)error;
 
-- (void) writeI64: (int64_t) value;
+-(BOOL) writeI64:(SInt64)value error:(NSError *__autoreleasing *)error;
 
-- (void) writeI16: (short) value;
+-(BOOL) writeI16:(short)value error:(NSError *__autoreleasing *)error;
 
-- (void) writeByte: (uint8_t) value;
+-(BOOL) writeByte:(UInt8)value error:(NSError *__autoreleasing *)error;
 
-- (void) writeString: (NSString *) value;
+-(BOOL) writeString:(NSString *)value error:(NSError *__autoreleasing *)error;
 
-- (void) writeDouble: (double) value;
+-(BOOL) writeDouble:(double)value error:(NSError *__autoreleasing *)error;
 
-- (void) writeBool: (BOOL) value;
+-(BOOL) writeBool:(BOOL)value error:(NSError *__autoreleasing *)error;
 
-- (void) writeBinary: (NSData *) data;
+-(BOOL) writeBinary:(NSData *)data error:(NSError *__autoreleasing *)error;
 
-- (void) writeFieldStop;
+-(BOOL) writeFieldStop:(NSError *__autoreleasing *)error;
 
-- (void) writeFieldEnd;
+-(BOOL) writeFieldEnd:(NSError *__autoreleasing *)error;
 
-- (void) writeMapBeginWithKeyType: (int) keyType
-                        valueType: (int) valueType
-                             size: (int) size;
-- (void) writeMapEnd;
+-(BOOL) writeMapBeginWithKeyType:(SInt32)keyType
+                       valueType:(SInt32)valueType
+                            size:(SInt32)size
+                           error:(NSError *__autoreleasing *)error;
+-(BOOL) writeMapEnd:(NSError *__autoreleasing *)error;
 
 
-- (void) writeSetBeginWithElementType: (int) elementType
-                                 size: (int) size;
-- (void) writeSetEnd;
+-(BOOL) writeSetBeginWithElementType:(SInt32)elementType
+                                size:(SInt32)size
+                               error:(NSError *__autoreleasing *)error;
+-(BOOL) writeSetEnd:(NSError *__autoreleasing *)error;
 
 
-- (void) writeListBeginWithElementType: (int) elementType
-                                  size: (int) size;
+-(BOOL) writeListBeginWithElementType:(SInt32)elementType
+                                 size:(SInt32)size
+                                error:(NSError *__autoreleasing *)error;
 
-- (void) writeListEnd;
+-(BOOL) writeListEnd:(NSError *__autoreleasing *)error;
 
 
 @end
 
+
+NS_ASSUME_NONNULL_END

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/protocol/TProtocolDecorator.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/protocol/TProtocolDecorator.h b/lib/cocoa/src/protocol/TProtocolDecorator.h
index 829bed6..369b6a2 100644
--- a/lib/cocoa/src/protocol/TProtocolDecorator.h
+++ b/lib/cocoa/src/protocol/TProtocolDecorator.h
@@ -21,10 +21,14 @@
 
 #import "TProtocol.h"
 
-@interface TProtocolDecorator : NSObject <TProtocol> {
-    id<TProtocol> mConcreteProtocol;
-}
+NS_ASSUME_NONNULL_BEGIN
 
-- (id) initWithProtocol: (id <TProtocol>) protocol;
+
+@interface TProtocolDecorator : NSObject <TProtocol>
+
+-(id) initWithProtocol:(id <TProtocol>)protocol;
 
 @end
+
+
+NS_ASSUME_NONNULL_END
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/protocol/TProtocolDecorator.m
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/protocol/TProtocolDecorator.m b/lib/cocoa/src/protocol/TProtocolDecorator.m
index e5acb6c..218f900 100644
--- a/lib/cocoa/src/protocol/TProtocolDecorator.m
+++ b/lib/cocoa/src/protocol/TProtocolDecorator.m
@@ -18,257 +18,278 @@
  */
 
 #import "TProtocolDecorator.h"
-#import "TObjective-C.h"
+
+
+@interface TProtocolDecorator ()
+
+@property(strong, nonatomic) id<TProtocol> concreteProtocol;
+
+@end
+
 
 @implementation TProtocolDecorator
 
-- (id) initWithProtocol: (id <TProtocol>) protocol
+-(id) initWithProtocol:(id <TProtocol>)protocol
 {
-    self = [super init];
-    if (self) {
-        mConcreteProtocol = [protocol retain_stub];
-    }
-    return self;
+  self = [super init];
+  if (self) {
+    _concreteProtocol = protocol;
+  }
+  return self;
 }
 
-- (id <TTransport>) transport
+-(id <TTransport>) transport
 {
-    return [mConcreteProtocol transport];
+  return [_concreteProtocol transport];
 }
 
-- (void) readMessageBeginReturningName: (NSString **) name
-                                  type: (int *) type
-                            sequenceID: (int *) sequenceID
+-(BOOL) readMessageBeginReturningName:(NSString **)name
+                                 type:(SInt32 *)type
+                           sequenceID:(SInt32 *)sequenceID
+                                error:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol readMessageBeginReturningName:name
-                                                type:type
-                                          sequenceID:sequenceID];
+  return [_concreteProtocol readMessageBeginReturningName:name
+                                                     type:type
+                                               sequenceID:sequenceID
+                                                    error:error];
 }
 
-- (void) readMessageEnd
+-(BOOL) readMessageEnd:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol readMessageEnd];
+  return [_concreteProtocol readMessageEnd:error];
 }
 
-- (void) readStructBeginReturningName: (NSString **) name
+-(BOOL) readStructBeginReturningName:(NSString **)name
+                               error:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol readStructBeginReturningName:name];
+  return [_concreteProtocol readStructBeginReturningName:name error:error];
 }
 
-- (void) readStructEnd
+-(BOOL) readStructEnd:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol readStructEnd];
+  return [_concreteProtocol readStructEnd:error];
 }
 
-- (void) readFieldBeginReturningName: (NSString **) name
-                                type: (int *) fieldType
-                             fieldID: (int *) fieldID
+-(BOOL) readFieldBeginReturningName:(NSString **)name
+                               type:(SInt32 *)fieldType
+                            fieldID:(SInt32 *)fieldID
+                              error:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol readFieldBeginReturningName:name
-                                              type:fieldType
-                                           fieldID:fieldID];
+  return [_concreteProtocol readFieldBeginReturningName:name
+                                                   type:fieldType
+                                                fieldID:fieldID
+                                                  error:error];
 }
-- (void) readFieldEnd
+-(BOOL) readFieldEnd:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol readFieldEnd];
+  return [_concreteProtocol readFieldEnd:error];
 }
 
-- (NSString *) readString
+-(BOOL) readString:(NSString *__autoreleasing *)value error:(NSError *__autoreleasing *)error
 {
-    return [mConcreteProtocol readString];
+  return [_concreteProtocol readString:value error:error];
 }
 
-- (BOOL) readBool
+-(BOOL) readBool:(BOOL *)value error:(NSError *__autoreleasing *)error
 {
-    return [mConcreteProtocol readBool];
+  return [_concreteProtocol readBool:value error:error];
 }
 
-- (unsigned char) readByte
+-(BOOL) readByte:(UInt8 *)value error:(NSError *__autoreleasing *)error
 {
-    return [mConcreteProtocol readByte];
+  return [_concreteProtocol readByte:value error:error];
 }
 
-- (short) readI16
+-(BOOL) readI16:(SInt16 *)value error:(NSError *__autoreleasing *)error
 {
-    return [mConcreteProtocol readI16];
+  return [_concreteProtocol readI16:value error:error];
 }
 
-- (int32_t) readI32
+-(BOOL) readI32:(SInt32 *)value error:(NSError *__autoreleasing *)error
 {
-    return [mConcreteProtocol readI32];
+  return [_concreteProtocol readI32:value error:error];
 }
 
-- (int64_t) readI64
+-(BOOL) readI64:(SInt64 *)value error:(NSError *__autoreleasing *)error
 {
-    return [mConcreteProtocol readI64];
+  return [_concreteProtocol readI64:value error:error];
 }
 
-- (double) readDouble
+-(BOOL) readDouble:(double *)value error:(NSError *__autoreleasing *)error
 {
-    return [mConcreteProtocol readDouble];
+  return [_concreteProtocol readDouble:value error:error];
 }
 
-- (NSData *) readBinary
+-(BOOL) readBinary:(NSData *__autoreleasing *)value error:(NSError *__autoreleasing *)error
 {
-    return [mConcreteProtocol readBinary];
+  return [_concreteProtocol readBinary:value error:error];
 }
 
-- (void) readMapBeginReturningKeyType: (int *) keyType
-                            valueType: (int *) valueType
-                                 size: (int *) size
+-(BOOL) readMapBeginReturningKeyType:(SInt32 *)keyType
+                           valueType:(SInt32 *)valueType
+                                size:(SInt32 *)size
+                               error:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol readMapBeginReturningKeyType:keyType
-                                          valueType:valueType
-                                               size:size];
+  return [_concreteProtocol readMapBeginReturningKeyType:keyType
+                                               valueType:valueType
+                                                    size:size
+                                                   error:error];
 }
-- (void) readMapEnd
+-(BOOL) readMapEnd:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol readMapEnd];
+  return [_concreteProtocol readMapEnd:error];
 }
 
 
-- (void) readSetBeginReturningElementType: (int *) elementType
-                                     size: (int *) size
+-(BOOL) readSetBeginReturningElementType:(SInt32 *)elementType
+                                    size:(SInt32 *)size
+                                   error:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol readSetBeginReturningElementType:elementType
-                                                   size:size];
+  return [_concreteProtocol readSetBeginReturningElementType:elementType
+                                                        size:size
+                                                       error:error];
 }
-- (void) readSetEnd
+-(BOOL) readSetEnd:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol readSetEnd];
+  return [_concreteProtocol readSetEnd:error];
 }
 
-- (void) readListBeginReturningElementType: (int *) elementType
-                                      size: (int *) size
+-(BOOL) readListBeginReturningElementType:(SInt32 *)elementType
+                                     size:(SInt32 *)size
+                                    error:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol readListBeginReturningElementType:elementType
-                                                    size:size];
+  return [_concreteProtocol readListBeginReturningElementType:elementType
+                                                         size:size
+                                                        error:error];
 }
-- (void) readListEnd
+-(BOOL) readListEnd:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol readListEnd];
+  return [_concreteProtocol readListEnd:error];
 }
 
-- (void) writeMessageBeginWithName: (NSString *) name
-                              type: (int) messageType
-                        sequenceID: (int) sequenceID
+-(BOOL) writeMessageBeginWithName:(NSString *)name
+                             type:(SInt32)messageType
+                       sequenceID:(SInt32)sequenceID
+                            error:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol writeMessageBeginWithName:name
-                                            type:messageType
-                                      sequenceID:sequenceID];
+  return [_concreteProtocol writeMessageBeginWithName:name
+                                                 type:messageType
+                                           sequenceID:sequenceID
+                                                error:error];
 }
-- (void) writeMessageEnd
+-(BOOL) writeMessageEnd:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol writeMessageEnd];
+  return [_concreteProtocol writeMessageEnd:error];
 }
 
-- (void) writeStructBeginWithName: (NSString *) name
+-(BOOL) writeStructBeginWithName:(NSString *)name error:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol writeStructBeginWithName:name];
+  return [_concreteProtocol writeStructBeginWithName:name error:error];
 }
-- (void) writeStructEnd
+-(BOOL) writeStructEnd:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol writeStructEnd];
+  return [_concreteProtocol writeStructEnd:error];
 }
 
-- (void) writeFieldBeginWithName: (NSString *) name
-                            type: (int) fieldType
-                         fieldID: (int) fieldID
+-(BOOL) writeFieldBeginWithName:(NSString *)name
+                           type:(SInt32)fieldType
+                        fieldID:(SInt32)fieldID
+                          error:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol writeFieldBeginWithName:name
-                                          type:fieldType
-                                       fieldID:fieldID];
+  return [_concreteProtocol writeFieldBeginWithName:name
+                                               type:fieldType
+                                            fieldID:fieldID
+                                              error:error];
 }
 
-- (void) writeI32: (int32_t) value
+-(BOOL) writeI32:(SInt32)value error:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol writeI32:value];
+  return [_concreteProtocol writeI32:value error:error];
 }
 
-- (void) writeI64: (int64_t) value
+-(BOOL) writeI64:(SInt64)value error:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol writeI64:value];
+  return [_concreteProtocol writeI64:value error:error];
 }
 
-- (void) writeI16: (short) value
+-(BOOL) writeI16:(SInt16)value error:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol writeI16:value];
+  return [_concreteProtocol writeI16:value error:error];
 }
 
-- (void) writeByte: (uint8_t) value
+-(BOOL) writeByte:(UInt8)value error:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol writeByte:value];
+  return [_concreteProtocol writeByte:value error:error];
 }
 
-- (void) writeString: (NSString *) value
+-(BOOL) writeString:(NSString *)value error:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol writeString:value];
+  return [_concreteProtocol writeString:value error:error];
 }
 
-- (void) writeDouble: (double) value
+-(BOOL) writeDouble:(double)value error:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol writeDouble:value];
+  return [_concreteProtocol writeDouble:value error:error];
 }
 
-- (void) writeBool: (BOOL) value
+-(BOOL) writeBool:(BOOL)value error:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol writeBool:value];
+  return [_concreteProtocol writeBool:value error:error];
 }
 
-- (void) writeBinary: (NSData *) data
+-(BOOL) writeBinary:(NSData *)data error:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol writeBinary:data];
+  return [_concreteProtocol writeBinary:data error:error];
 }
 
-- (void) writeFieldStop
+-(BOOL) writeFieldStop:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol writeFieldStop];
+  return [_concreteProtocol writeFieldStop:error];
 }
 
-- (void) writeFieldEnd
+-(BOOL) writeFieldEnd:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol writeFieldEnd];
+  return [_concreteProtocol writeFieldEnd:error];
 }
 
-- (void) writeMapBeginWithKeyType: (int) keyType
-                        valueType: (int) valueType
-                             size: (int) size
-{
-    [mConcreteProtocol writeMapBeginWithKeyType:keyType
-                                      valueType:valueType
-                                           size:size];
-}
-- (void) writeMapEnd
+-(BOOL) writeMapBeginWithKeyType:(SInt32)keyType
+                       valueType:(SInt32)valueType
+                            size:(SInt32)size
+                           error:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol writeMapEnd];
+  return [_concreteProtocol writeMapBeginWithKeyType:keyType
+                                           valueType:valueType
+                                                size:size
+                                               error:error];
 }
 
-- (void) writeSetBeginWithElementType: (int) elementType
-                                 size: (int) size
+-(BOOL) writeMapEnd:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol writeSetBeginWithElementType:elementType size:size];
+  return [_concreteProtocol writeMapEnd:error];
 }
 
-- (void) writeSetEnd
+-(BOOL) writeSetBeginWithElementType:(SInt32)elementType
+                                size:(SInt32)size
+                               error:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol writeSetEnd];
+  return [_concreteProtocol writeSetBeginWithElementType:elementType size:size error:error];
 }
 
-- (void) writeListBeginWithElementType: (int) elementType
-                                  size: (int) size
+-(BOOL) writeSetEnd:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol writeListBeginWithElementType:elementType size:size];
+  return [_concreteProtocol writeSetEnd:error];
 }
 
-- (void) writeListEnd
+-(BOOL) writeListBeginWithElementType:(SInt32)elementType
+                                 size:(SInt32)size
+                                error:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol writeListEnd];
+  return [_concreteProtocol writeListBeginWithElementType:elementType size:size error:error];
 }
 
-- (void) dealloc
+-(BOOL) writeListEnd:(NSError *__autoreleasing *)error
 {
-    [mConcreteProtocol release_stub];
-    [super dealloc_stub];
+  return [_concreteProtocol writeListEnd:error];
 }
 
 @end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/protocol/TProtocolError.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/protocol/TProtocolError.h b/lib/cocoa/src/protocol/TProtocolError.h
new file mode 100644
index 0000000..ab0bc40
--- /dev/null
+++ b/lib/cocoa/src/protocol/TProtocolError.h
@@ -0,0 +1,76 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#import "TError.h"
+
+
+extern NSString *TProtocolErrorDomain;
+
+typedef NS_ENUM (int, TProtocolError) {
+  TProtocolErrorUnknown                   = 0,
+  TProtocolErrorInvalidData               = 1,
+  TProtocolErrorNegativeSize              = 2,
+  TProtocolErrorSizeLimit                 = 3,
+  TProtocolErrorBadVersion                = 4,
+  TProtocolErrorNotImplemented            = 5,
+  TProtocolErrorDepthLimit                = 6,
+};
+
+
+typedef NS_ENUM(int, TProtocolExtendedError) {
+  TProtocolExtendedErrorMissingRequiredField  = 1001,
+  TProtocolExtendedErrorUnexpectedType        = 1002,
+  TProtocolExtendedErrorMismatchedProtocol    = 1003,
+};
+
+extern NSString *TProtocolErrorExtendedErrorKey;
+extern NSString *TProtocolErrorFieldNameKey;
+extern NSString *TProtocolErrorExpectedIdKey;
+extern NSString *TProtocolErrorExpectedVersionKey;
+extern NSString *TProtocolErrorTypeKey;
+extern NSString *TProtocolErrorSourceLineKey;
+extern NSString *TProtocolErrorSourceFileKey;
+extern NSString *TProtocolErrorSourceMethodKey;
+extern NSString *TProtocolErrorMessageNameKey;
+
+
+#define PROTOCOL_ERROR(ret, err, ...) \
+  if (error) {  \
+    *error = [NSError errorWithDomain:TProtocolErrorDomain \
+                                 code:TProtocolError ## err \
+                             userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:__VA_ARGS__], \
+                                        @"SourceFile": [NSString stringWithUTF8String:__FILE__], \
+                                        @"SourceLine": @(__LINE__), \
+                                        @"SourceFunction": [NSString stringWithUTF8String:__PRETTY_FUNCTION__], \
+                                        @"Message": self.currentMessageName ? self.currentMessageName : @""}]; \
+  } \
+  return ret
+
+#define PROTOCOL_TRANSPORT_ERROR(ret, errorPtr, ...) \
+  if (errorPtr) { \
+    *error = [NSError errorWithDomain:TProtocolErrorDomain \
+                                 code:TProtocolErrorUnknown \
+                             userInfo:@{NSLocalizedDescriptionKey: [[NSString stringWithFormat:__VA_ARGS__] stringByAppendingFormat:@": %@", [(*errorPtr) localizedDescription]], \
+                                        TProtocolErrorSourceFileKey: [NSString stringWithUTF8String:__FILE__], \
+                                        TProtocolErrorSourceLineKey: @(__LINE__), \
+                                        TProtocolErrorSourceMethodKey: [NSString stringWithUTF8String:__PRETTY_FUNCTION__], \
+                                        TProtocolErrorMessageNameKey: self.currentMessageName ? self.currentMessageName : @"", \
+                                        NSUnderlyingErrorKey: *errorPtr}]; \
+  } \
+  return ret

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/protocol/TProtocolError.m
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/protocol/TProtocolError.m b/lib/cocoa/src/protocol/TProtocolError.m
new file mode 100644
index 0000000..953673b
--- /dev/null
+++ b/lib/cocoa/src/protocol/TProtocolError.m
@@ -0,0 +1,33 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#import "TProtocolError.h"
+
+
+NSString *TProtocolErrorDomain = @"TProtocolErrorDomain";
+
+NSString *TProtocolErrorExtendedErrorKey = @"extendedError";
+NSString *TProtocolErrorFieldNameKey = @"field";
+NSString *TProtocolErrorExpectedIdKey = @"expectedId";
+NSString *TProtocolErrorExpectedVersionKey = @"expectedVersion";
+NSString *TProtocolErrorTypeKey = @"type";
+NSString *TProtocolErrorSourceLineKey = @"sourceLine";
+NSString *TProtocolErrorSourceFileKey = @"sourceFile";
+NSString *TProtocolErrorSourceMethodKey = @"sourceMethod";
+NSString *TProtocolErrorMessageNameKey = @"messageName";

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/protocol/TProtocolException.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/protocol/TProtocolException.h b/lib/cocoa/src/protocol/TProtocolException.h
deleted file mode 100644
index ad354fc..0000000
--- a/lib/cocoa/src/protocol/TProtocolException.h
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#import "TException.h"
-
-@interface TProtocolException : TException {
-}
-
-@end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/protocol/TProtocolException.m
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/protocol/TProtocolException.m b/lib/cocoa/src/protocol/TProtocolException.m
deleted file mode 100644
index 681487a..0000000
--- a/lib/cocoa/src/protocol/TProtocolException.m
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#import "TProtocolException.h"
-
-@implementation TProtocolException
-@end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/protocol/TProtocolFactory.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/protocol/TProtocolFactory.h b/lib/cocoa/src/protocol/TProtocolFactory.h
index f200a6d..a022a7f 100644
--- a/lib/cocoa/src/protocol/TProtocolFactory.h
+++ b/lib/cocoa/src/protocol/TProtocolFactory.h
@@ -21,9 +21,16 @@
 #import "TProtocol.h"
 #import "TTransport.h"
 
+NS_ASSUME_NONNULL_BEGIN
+
 
 @protocol TProtocolFactory <NSObject>
 
-- (id <TProtocol>) newProtocolOnTransport: (id <TTransport>) transport;
+@property (readonly, nonatomic) NSString *protocolName;
+
+-(id<TProtocol>) newProtocolOnTransport:(id<TTransport>)transport;
 
 @end
+
+
+NS_ASSUME_NONNULL_END

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/protocol/TProtocolUtil.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/protocol/TProtocolUtil.h b/lib/cocoa/src/protocol/TProtocolUtil.h
index 757748a..82510cf 100644
--- a/lib/cocoa/src/protocol/TProtocolUtil.h
+++ b/lib/cocoa/src/protocol/TProtocolUtil.h
@@ -20,10 +20,14 @@
 #import "TProtocol.h"
 #import "TTransport.h"
 
-@interface TProtocolUtil : NSObject {
+NS_ASSUME_NONNULL_BEGIN
 
-}
 
-+ (void) skipType: (int) type onProtocol: (id <TProtocol>) protocol;
+@interface TProtocolUtil : NSObject
 
-@end
++(BOOL) skipType:(int)type onProtocol:(id <TProtocol>)protocol error:(NSError **)error;
+
+@end;
+
+
+NS_ASSUME_NONNULL_END
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/protocol/TProtocolUtil.m
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/protocol/TProtocolUtil.m b/lib/cocoa/src/protocol/TProtocolUtil.m
index 13d7095..c0d65ac 100644
--- a/lib/cocoa/src/protocol/TProtocolUtil.m
+++ b/lib/cocoa/src/protocol/TProtocolUtil.m
@@ -21,84 +21,151 @@
 
 @implementation TProtocolUtil
 
-+ (void) skipType: (int) type onProtocol: (id <TProtocol>) protocol
++(BOOL) skipType:(int)type onProtocol:(id <TProtocol>)protocol error:(NSError **)error
 {
   switch (type) {
-  case TType_BOOL:
-    [protocol readBool];
-    break;
-  case TType_BYTE:
-    [protocol readByte];
-    break;
-  case TType_I16:
-    [protocol readI16];
-    break;
-  case TType_I32:
-    [protocol readI32];
-    break;
-  case TType_I64:
-    [protocol readI64];
-    break;
-  case TType_DOUBLE:
-    [protocol readDouble];
-    break;
-  case TType_STRING:
-    [protocol readString];
-    break;
-  case TType_STRUCT:
-    [protocol readStructBeginReturningName: NULL];
+  case TTypeBOOL: {
+    BOOL val;
+    if (![protocol readBool:&val error:error]) {
+      return NO;
+    }
+  }
+  break;
+
+  case TTypeBYTE: {
+    UInt8 val;
+    if (![protocol readByte:&val error:error]) {
+      return NO;
+    }
+  }
+  break;
+
+  case TTypeI16: {
+    SInt16 val;
+    if (![protocol readI16:&val error:error]) {
+      return NO;
+    }
+  }
+  break;
+
+  case TTypeI32: {
+    SInt32 val;
+    if (![protocol readI32:&val error:error]) {
+      return NO;
+    }
+  }
+  break;
+
+  case TTypeI64: {
+    SInt64 val;
+    if (![protocol readI64:&val error:error]) {
+      return NO;
+    }
+  }
+  break;
+
+  case TTypeDOUBLE: {
+    double val;
+    if (![protocol readDouble:&val error:error]) {
+      return NO;
+    }
+  }
+  break;
+
+  case TTypeSTRING: {
+    NSString *val;
+    if (![protocol readString:&val error:error]) {
+      return NO;
+    }
+  }
+  break;
+
+  case TTypeSTRUCT: {
+    if (![protocol readStructBeginReturningName:NULL error:error]) {
+      return NO;
+    }
     while (true) {
-      int fieldType;
-      [protocol readFieldBeginReturningName: nil type: &fieldType fieldID: nil];
-      if (fieldType == TType_STOP) {
+      SInt32 fieldType;
+      if (![protocol readFieldBeginReturningName:nil type:&fieldType fieldID:nil error:error]) {
+        return NO;
+      }
+      if (fieldType == TTypeSTOP) {
         break;
       }
-      [TProtocolUtil skipType: fieldType onProtocol: protocol];
-      [protocol readFieldEnd];
-    }
-    [protocol readStructEnd];
-    break;
-  case TType_MAP:
-  {
-    int keyType;
-    int valueType;
-    int size;
-    [protocol readMapBeginReturningKeyType: &keyType valueType: &valueType size: &size];
+      if (![self skipType:fieldType onProtocol:protocol error:error]) {
+        return NO;
+      }
+      if (![protocol readFieldEnd:error]) {
+        return NO;
+      }
+    }
+    if (![protocol readStructEnd:error]) {
+      return NO;
+    }
+  }
+  break;
+
+  case TTypeMAP: {
+    SInt32 keyType;
+    SInt32 valueType;
+    SInt32 size;
+    if (![protocol readMapBeginReturningKeyType:&keyType valueType:&valueType size:&size error:error]) {
+      return NO;
+    }
     int i;
     for (i = 0; i < size; i++) {
-      [TProtocolUtil skipType: keyType onProtocol: protocol];
-      [TProtocolUtil skipType: valueType onProtocol: protocol];
+      if (![TProtocolUtil skipType:keyType onProtocol:protocol error:error]) {
+        return NO;
+      }
+      if (![TProtocolUtil skipType:valueType onProtocol:protocol error:error]) {
+        return NO;
+      }
+    }
+    if (![protocol readMapEnd:error]) {
+      return NO;
     }
-    [protocol readMapEnd];
   }
-    break;
-    case TType_SET:
-    {
-      int elemType;
-      int size;
-      [protocol readSetBeginReturningElementType: &elemType size: &size];
-      int i;
-      for (i = 0; i < size; i++) {
-        [TProtocolUtil skipType: elemType onProtocol: protocol];
+  break;
+
+  case TTypeSET: {
+    SInt32 elemType;
+    SInt32 size;
+    if (![protocol readSetBeginReturningElementType:&elemType size:&size error:error]) {
+      return NO;
+    }
+    int i;
+    for (i = 0; i < size; i++) {
+      if (![TProtocolUtil skipType:elemType onProtocol:protocol error:error]) {
+        return NO;
       }
-      [protocol readSetEnd];
-    }
-      break;
-    case TType_LIST:
-    {
-      int elemType;
-      int size;
-      [protocol readListBeginReturningElementType: &elemType size: &size];
-      int i;
-      for (i = 0; i < size; i++) {
-        [TProtocolUtil skipType: elemType onProtocol: protocol];
+    }
+    if (![protocol readSetEnd:error]) {
+      return NO;
+    }
+  }
+  break;
+
+  case TTypeLIST: {
+    SInt32 elemType;
+    SInt32 size;
+    if (![protocol readListBeginReturningElementType:&elemType size:&size error:error]) {
+      return NO;
+    }
+    int i;
+    for (i = 0; i < size; i++) {
+      if (![TProtocolUtil skipType:elemType onProtocol:protocol error:error]) {
+        return NO;
       }
-      [protocol readListEnd];
     }
-      break;
-    default:
-      return;
+    if (![protocol readListEnd:error]) {
+      return NO;
+    }
   }
+  break;
+
+  }
+
+  return YES;
 }
 
 @end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/server/TSocketServer.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/server/TSocketServer.h b/lib/cocoa/src/server/TSocketServer.h
index c8ff9f0..fe657ea 100644
--- a/lib/cocoa/src/server/TSocketServer.h
+++ b/lib/cocoa/src/server/TSocketServer.h
@@ -27,23 +27,21 @@
 #import <CFNetwork/CFNetwork.h>
 #endif
 
-extern NSString * const kTSocketServer_ClientConnectionFinishedForProcessorNotification;
-extern NSString * const kTSocketServer_ProcessorKey;
-extern NSString * const kTSockerServer_TransportKey;
+NS_ASSUME_NONNULL_BEGIN
 
 
-@interface TSocketServer : NSObject {
-  NSFileHandle * mSocketFileHandle;
-  id <TProtocolFactory> mInputProtocolFactory;
-  id <TProtocolFactory> mOutputProtocolFactory;
-  id <TProcessorFactory> mProcessorFactory;
-}
+extern NSString *const TSocketServerClientConnectionFinished;
+extern NSString *const TSocketServerProcessorKey;
+extern NSString *const TSockerServerTransportKey;
 
-- (id) initWithPort: (int) port
-    protocolFactory: (id <TProtocolFactory>) protocolFactory
-   processorFactory: (id <TProcessorFactory>) processorFactory;
 
-@end
+@interface TSocketServer : NSObject
+
+-(instancetype) initWithPort:(int)port
+             protocolFactory:(id <TProtocolFactory>)protocolFactory
+            processorFactory:(id <TProcessorFactory>)processorFactory;
 
+@end
 
 
+NS_ASSUME_NONNULL_END


[2/7] thrift git commit: THRIFT-2905 Cocoa compiler should have option to produce "modern" Objective-C Client: Cocoa (ObjectiveC & Swift) Author: Kevin Wooten

Posted by je...@apache.org.
http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/server/TSocketServer.m
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/server/TSocketServer.m b/lib/cocoa/src/server/TSocketServer.m
index 07bc829..ccbbba1 100644
--- a/lib/cocoa/src/server/TSocketServer.m
+++ b/lib/cocoa/src/server/TSocketServer.m
@@ -21,37 +21,51 @@
 #import "TSocketServer.h"
 #import "TNSFileHandleTransport.h"
 #import "TProtocol.h"
-#import "TTransportException.h"
-#import "TObjective-C.h"
+#import "TTransportError.h"
+
 #import <sys/socket.h>
 #include <netinet/in.h>
 
 
 
-NSString * const kTSocketServer_ClientConnectionFinishedForProcessorNotification = @"TSocketServer_ClientConnectionFinishedForProcessorNotification";
-NSString * const kTSocketServer_ProcessorKey = @"TSocketServer_Processor";
-NSString * const kTSockerServer_TransportKey = @"TSockerServer_Transport";
+NSString *const TSocketServerClientConnectionFinished = @"TSocketServerClientConnectionFinished";
+NSString *const TSocketServerProcessorKey = @"TSocketServerProcessor";
+NSString *const TSockerServerTransportKey = @"TSockerServerTransport";
+
+
+@interface TSocketServer ()
+
+@property(strong, nonatomic) id<TProtocolFactory> inputProtocolFactory;
+@property(strong, nonatomic) id<TProtocolFactory> outputProtocolFactory;
+@property(strong, nonatomic) id<TProcessorFactory> processorFactory;
+@property(strong, nonatomic) NSFileHandle *socketFileHandle;
+@property(strong, nonatomic) dispatch_queue_t processingQueue;
+
+@end
 
 
 @implementation TSocketServer
 
-- (id) initWithPort: (int) port
-    protocolFactory: (id <TProtocolFactory>) protocolFactory
-   processorFactory: (id <TProcessorFactory>) processorFactory
+-(instancetype) initWithPort:(int)port
+             protocolFactory:(id <TProtocolFactory>)protocolFactory
+            processorFactory:(id <TProcessorFactory>)processorFactory;
 {
   self = [super init];
 
-  mInputProtocolFactory = [protocolFactory retain_stub];
-  mOutputProtocolFactory = [protocolFactory retain_stub];
-  mProcessorFactory = [processorFactory retain_stub];
+  _inputProtocolFactory = protocolFactory;
+  _outputProtocolFactory = protocolFactory;
+  _processorFactory = processorFactory;
+
+  dispatch_queue_attr_t processingQueueAttr =
+    dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_CONCURRENT, QOS_CLASS_BACKGROUND, 0);
+
+  _processingQueue = dispatch_queue_create("TSocketServer.processing", processingQueueAttr);
 
   // create a socket.
   int fd = -1;
   CFSocketRef socket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP, 0, NULL, NULL);
   if (socket) {
-    CFOptionFlags flagsToClear = kCFSocketCloseOnInvalidate;
-    CFSocketSetSocketFlags(socket,  CFSocketGetSocketFlags(socket) & ~flagsToClear);
-
+    CFSocketSetSocketFlags(socket, CFSocketGetSocketFlags(socket) & ~kCFSocketCloseOnInvalidate);
     fd = CFSocketGetNative(socket);
     int yes = 1;
     setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void *)&yes, sizeof(yes));
@@ -63,135 +77,88 @@ NSString * const kTSockerServer_TransportKey = @"TSockerServer_Transport";
     addr.sin_port = htons(port);
     addr.sin_addr.s_addr = htonl(INADDR_ANY);
     NSData *address = [NSData dataWithBytes:&addr length:sizeof(addr)];
-    if (CFSocketSetAddress(socket, (bridge_stub CFDataRef)address) != kCFSocketSuccess) {
+    if (CFSocketSetAddress(socket, (__bridge CFDataRef)address) != kCFSocketSuccess) {
       CFSocketInvalidate(socket);
       CFRelease(socket);
-      NSLog(@"*** Could not bind to address");
+      NSLog(@"TSocketServer: Could not bind to address");
       return nil;
     }
-  } else {
-    NSLog(@"*** No server socket");
+  }
+  else {
+    NSLog(@"TSocketServer: No server socket");
     return nil;
   }
-  
+
   // wrap it in a file handle so we can get messages from it
-  mSocketFileHandle = [[NSFileHandle alloc] initWithFileDescriptor: fd
-                                                    closeOnDealloc: YES];
-  
+  _socketFileHandle = [[NSFileHandle alloc] initWithFileDescriptor:fd
+                                                    closeOnDealloc:YES];
+
   // throw away our socket
   CFSocketInvalidate(socket);
   CFRelease(socket);
-  
-    // register for notifications of accepted incoming connections
-  [[NSNotificationCenter defaultCenter] addObserver: self
-                                           selector: @selector(connectionAccepted:)
-                                               name: NSFileHandleConnectionAcceptedNotification
-                                             object: mSocketFileHandle];
-  
+
+  // register for notifications of accepted incoming connections
+  [[NSNotificationCenter defaultCenter] addObserver:self
+                                           selector:@selector(connectionAccepted:)
+                                               name:NSFileHandleConnectionAcceptedNotification
+                                             object:_socketFileHandle];
+
   // tell socket to listen
-  [mSocketFileHandle acceptConnectionInBackgroundAndNotify];
-  
-  NSLog(@"Listening on TCP port %d", port);
-  
+  [_socketFileHandle acceptConnectionInBackgroundAndNotify];
+
+  NSLog(@"TSocketServer: Listening on TCP port %d", port);
+
   return self;
 }
 
 
-- (void) dealloc {
+-(void) dealloc
+{
   [[NSNotificationCenter defaultCenter] removeObserver:self];
-  [mInputProtocolFactory release_stub];
-  [mOutputProtocolFactory release_stub];
-  [mProcessorFactory release_stub];
-  [mSocketFileHandle release_stub];
-  [super dealloc_stub];
 }
 
 
-- (void) connectionAccepted: (NSNotification *) aNotification
+-(void) connectionAccepted:(NSNotification *)notification
 {
-  NSFileHandle * socket = [[aNotification userInfo] objectForKey: NSFileHandleNotificationFileHandleItem];
+  NSFileHandle *socket = [notification.userInfo objectForKey:NSFileHandleNotificationFileHandleItem];
+
+  // Now that we have a client connected, handle request on queue
+  dispatch_async(_processingQueue, ^{
 
-  // now that we have a client connected, spin off a thread to handle activity
-  [NSThread detachNewThreadSelector: @selector(handleClientConnection:)
-                           toTarget: self
-                         withObject: socket];
+    [self handleClientConnection:socket];
 
-  [[aNotification object] acceptConnectionInBackgroundAndNotify];
+  });
+
+  // Continue accepting connections
+  [_socketFileHandle acceptConnectionInBackgroundAndNotify];
 }
 
 
-- (void) handleClientConnection: (NSFileHandle *) clientSocket
+-(void) handleClientConnection:(NSFileHandle *)clientSocket
 {
-#if __has_feature(objc_arc)
-    @autoreleasepool {
-        TNSFileHandleTransport * transport = [[TNSFileHandleTransport alloc] initWithFileHandle: clientSocket];
-        id<TProcessor> processor = [mProcessorFactory processorForTransport: transport];
-        
-        id <TProtocol> inProtocol = [mInputProtocolFactory newProtocolOnTransport: transport];
-        id <TProtocol> outProtocol = [mOutputProtocolFactory newProtocolOnTransport: transport];
-        
-        @try {
-            BOOL result = NO;
-            do {
-                @autoreleasepool {
-                    result = [processor processOnInputProtocol: inProtocol outputProtocol: outProtocol];
-                }
-            } while (result);
-        }
-        @catch (TTransportException * te) {
-            (void)te;
-            //NSLog(@"Caught transport exception, abandoning client connection: %@", te);
-        }
-        
-        NSNotification * n = [NSNotification notificationWithName: kTSocketServer_ClientConnectionFinishedForProcessorNotification
-                                                           object: self
-                                                         userInfo: [NSDictionary dictionaryWithObjectsAndKeys: 
-                                                                    processor,
-                                                                    kTSocketServer_ProcessorKey,
-                                                                    transport,
-                                                                    kTSockerServer_TransportKey,
-                                                                    nil]];
-        [[NSNotificationCenter defaultCenter] performSelectorOnMainThread: @selector(postNotification:) withObject: n waitUntilDone: YES];
-        
-    }
-#else
-  NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
-  
-  TNSFileHandleTransport * transport = [[TNSFileHandleTransport alloc] initWithFileHandle: clientSocket];
-  id<TProcessor> processor = [mProcessorFactory processorForTransport: transport];
-  
-  id <TProtocol> inProtocol = [[mInputProtocolFactory newProtocolOnTransport: transport] autorelease];
-  id <TProtocol> outProtocol = [[mOutputProtocolFactory newProtocolOnTransport: transport] autorelease];
-
-  @try {
-    BOOL result = NO;
-    do {
-      NSAutoreleasePool * myPool = [[NSAutoreleasePool alloc] init];
-      result = [processor processOnInputProtocol: inProtocol outputProtocol: outProtocol];
-      [myPool release];
-    } while (result);
-  }
-  @catch (TTransportException * te) {
-    //NSLog(@"Caught transport exception, abandoning client connection: %@", te);
-  }
+  @autoreleasepool {
 
-  NSNotification * n = [NSNotification notificationWithName: kTSocketServer_ClientConnectionFinishedForProcessorNotification
-                                                     object: self
-                                                   userInfo: [NSDictionary dictionaryWithObjectsAndKeys: 
-                                                              processor,
-                                                              kTSocketServer_ProcessorKey,
-                                                              transport,
-                                                              kTSockerServer_TransportKey,
-                                                              nil]];
-  [[NSNotificationCenter defaultCenter] performSelectorOnMainThread: @selector(postNotification:) withObject: n waitUntilDone: YES];
-  
-  [pool release];
-#endif
-}
+    TNSFileHandleTransport *transport = [[TNSFileHandleTransport alloc] initWithFileHandle:clientSocket];
+    id<TProcessor> processor = [_processorFactory processorForTransport:transport];
 
+    id <TProtocol> inProtocol = [_inputProtocolFactory newProtocolOnTransport:transport];
+    id <TProtocol> outProtocol = [_outputProtocolFactory newProtocolOnTransport:transport];
 
+    NSError *error;
+    if (![processor processOnInputProtocol:inProtocol outputProtocol:outProtocol error:&error]) {
+      // Handle error
+      NSLog(@"Error processing request: %@", error);
+    }
 
-@end
+    dispatch_async(dispatch_get_main_queue(), ^{
 
+      [NSNotificationCenter.defaultCenter postNotificationName:TSocketServerClientConnectionFinished
+                                                        object:self
+                                                      userInfo:@{TSocketServerProcessorKey: processor,
+                                                                 TSockerServerTransportKey: transport}];
+    });
 
+  }
+}
 
+@end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/TAsyncTransport.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/TAsyncTransport.h b/lib/cocoa/src/transport/TAsyncTransport.h
index f75b701..bab4fbd 100644
--- a/lib/cocoa/src/transport/TAsyncTransport.h
+++ b/lib/cocoa/src/transport/TAsyncTransport.h
@@ -18,12 +18,29 @@
  */
 
 #import "TTransport.h"
-#import "TException.h"
 
-typedef void(^TAsyncFailureBlock)(TException *);
+NS_ASSUME_NONNULL_BEGIN
+
+
+@protocol TAsyncTransport;
+
+
+@protocol TAsyncTransportFactory <NSObject>
+
+-(id<TAsyncTransport>) newTransport;
+
+@end
+
+
+typedef void (^TAsyncCompletionBlock)();
+typedef void (^TAsyncFailureBlock)(NSError * __nonnull);
+
 
 @protocol TAsyncTransport <TTransport>
 
-- (void) flush:(dispatch_block_t)flushed failure:(TAsyncFailureBlock)failure;
+-(void) flushWithCompletion:(TAsyncCompletionBlock)completed failure:(TAsyncFailureBlock)failure;
 
 @end
+
+
+NS_ASSUME_NONNULL_END
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/TFramedTransport.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/TFramedTransport.h b/lib/cocoa/src/transport/TFramedTransport.h
index fc38877..ea68ac4 100644
--- a/lib/cocoa/src/transport/TFramedTransport.h
+++ b/lib/cocoa/src/transport/TFramedTransport.h
@@ -20,10 +20,14 @@
 #import <Foundation/Foundation.h>
 #import "TTransport.h"
 
-@interface TFramedTransport : NSObject <TTransport> {
-    id <TTransport> mTransport;
-}
+NS_ASSUME_NONNULL_BEGIN
 
-- (id) initWithTransport: (id <TTransport>) transport;
+
+@interface TFramedTransport : NSObject <TTransport>
+
+-(id) initWithTransport:(id <TTransport>)transport;
 
 @end
+
+
+NS_ASSUME_NONNULL_END

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/TFramedTransport.m
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/TFramedTransport.m b/lib/cocoa/src/transport/TFramedTransport.m
index 2148806..4db65c4 100644
--- a/lib/cocoa/src/transport/TFramedTransport.m
+++ b/lib/cocoa/src/transport/TFramedTransport.m
@@ -18,126 +18,163 @@
  */
 
 #import "TFramedTransport.h"
-#import "TTransportException.h"
-#import "TObjective-C.h"
+#import "TTransportError.h"
 
 #define HEADER_SIZE 4
 #define INIT_FRAME_SIZE 1024
 
-@implementation TFramedTransport {
-    NSMutableData* writeBuffer;
-    NSMutableData* readBuffer;
-    NSUInteger readOffset;
-    uint8_t dummy_header[HEADER_SIZE];
-}
 
-- (id) initWithTransport:(id <TTransport>)transport
-{
-    mTransport = [transport retain_stub];
-    readBuffer = nil;
-    readOffset = 0;
-    writeBuffer = [[NSMutableData alloc] initWithCapacity:INIT_FRAME_SIZE];
-    [writeBuffer appendBytes:dummy_header length:HEADER_SIZE];
-    return self;
-}
+@interface TFramedTransport ()
+
+@property(strong, nonatomic) id<TTransport> transport;
+@property(strong, nonatomic) NSMutableData *writeBuffer;
+@property(strong, nonatomic) NSMutableData *readBuffer;
+@property(assign, nonatomic) NSUInteger readOffset;
+
+@end
+
+
+@implementation TFramedTransport
 
-- (void) dealloc
+-(id) initWithTransport:(id <TTransport>)aTransport
 {
-    [mTransport release_stub];
-    [writeBuffer release_stub];
-    if (readBuffer != nil)
-        [readBuffer release_stub];
-    [super dealloc_stub];
+  if ((self = [self init])) {
+    _transport = aTransport;
+    _readBuffer = nil;
+    _readOffset = 0;
+    _writeBuffer = [NSMutableData dataWithLength:HEADER_SIZE];
+  }
+  return self;
 }
 
-- (void)flush
+-(BOOL) flush:(NSError **)error
 {
-    size_t headerAndDataLength = [writeBuffer length];
-    if (headerAndDataLength < HEADER_SIZE) {
-        @throw [TTransportException exceptionWithReason:@"Framed transport buffer has no header"];
+  int len = (int)[_writeBuffer length];
+  int data_len = len - HEADER_SIZE;
+  if (data_len < 0) {
+    if (error) {
+      *error = [NSError errorWithDomain:TTransportErrorDomain
+                                   code:TTransportErrorUnknown
+                               userInfo:@{}];
     }
+    return NO;
+  }
 
-    size_t dataLength = headerAndDataLength - HEADER_SIZE;
-    uint8_t i32rd[HEADER_SIZE];
-    i32rd[0] = (uint8_t)(0xff & (dataLength >> 24));
-    i32rd[1] = (uint8_t)(0xff & (dataLength >> 16));
-    i32rd[2] = (uint8_t)(0xff & (dataLength >> 8));
-    i32rd[3] = (uint8_t)(0xff & (dataLength));
-
-    // should we make a copy of the writeBuffer instead? Better for threaded operations!
-    [writeBuffer replaceBytesInRange:NSMakeRange(0, HEADER_SIZE) withBytes:i32rd length:HEADER_SIZE];
-    [mTransport write:[writeBuffer mutableBytes] offset:0 length:headerAndDataLength];
-    [mTransport flush];
-
-    // reuse old memory buffer
-    [writeBuffer setLength:0];
-    [writeBuffer appendBytes:dummy_header length:HEADER_SIZE];
+  UInt8 i32rd[HEADER_SIZE];
+  i32rd[0] = (UInt8)(0xff & (data_len >> 24));
+  i32rd[1] = (UInt8)(0xff & (data_len >> 16));
+  i32rd[2] = (UInt8)(0xff & (data_len >> 8));
+  i32rd[3] = (UInt8)(0xff & (data_len));
+
+  // should we make a copy of the writeBuffer instead? Better for threaded
+  //  operations!
+  [_writeBuffer replaceBytesInRange:NSMakeRange(0, HEADER_SIZE)
+                          withBytes:i32rd length:HEADER_SIZE];
+
+  if (![_transport write:_writeBuffer.mutableBytes offset:0 length:len error:error]) {
+    return NO;
+  }
+
+  if (![_transport flush:error]) {
+    return NO;
+  }
+
+  _writeBuffer.length = HEADER_SIZE;
+
+  return YES;
 }
 
-- (void) write: (const uint8_t *) data offset: (size_t) offset length: (size_t) length
+-(BOOL) write:(const UInt8 *)data offset:(UInt32)offset length:(UInt32)length error:(NSError *__autoreleasing *)error
 {
-    [writeBuffer appendBytes:data+offset length:length];
+  [_writeBuffer appendBytes:data+offset length:length];
+
+  return YES;
 }
 
-- (size_t) readAll: (uint8_t *) buf offset: (size_t) offset length: (size_t) length
+-(BOOL) readAll:(UInt8 *)outBuffer offset:(UInt32)outBufferOffset length:(UInt32)length error:(NSError *__autoreleasing *)error
 {
-    if (readBuffer == nil) {
-        [self readFrame];
+  UInt32 got = [self readAvail:outBuffer offset:outBufferOffset maxLength:length error:error];
+  if (got != length) {
+
+    // Report underflow only if readAvail didn't report error already
+    if (error && !*error) {
+      *error = [NSError errorWithDomain:TTransportErrorDomain
+                                   code:TTransportErrorEndOfFile
+                               userInfo:nil];
     }
-    
-    if (readBuffer != nil) {
-        size_t bufferLength = [readBuffer length];
-        if (bufferLength - readOffset >= length) {
-            [readBuffer getBytes:buf range:NSMakeRange(readOffset,length)]; // copy data
-            readOffset += length;
-        } else {
-            // void the previous readBuffer data and request a new frame
-            [self readFrame];
-            [readBuffer getBytes:buf range:NSMakeRange(0,length)]; // copy data
-            readOffset = length;
-        }
-    }
-    return length;
+
+    return NO;
+  }
+
+  return YES;
 }
 
-- (void)readFrame
+-(UInt32) readAvail:(UInt8 *)outBuffer offset:(UInt32)outBufferOffset maxLength:(UInt32)length error:(NSError *__autoreleasing *)error
 {
-    uint8_t i32rd[HEADER_SIZE];
-    [mTransport readAll: i32rd offset: 0 length: HEADER_SIZE];
-    int32_t headerValue =
-        ((i32rd[0] & 0xff) << 24) |
-        ((i32rd[1] & 0xff) << 16) |
-        ((i32rd[2] & 0xff) <<  8) |
-        ((i32rd[3] & 0xff));
-    if (headerValue < 0) {
-        NSString *reason = [NSString stringWithFormat:
-                            @"Frame header reports negative frame size: %"PRId32,
-                            headerValue];
-        @throw [TTransportException exceptionWithReason:reason];
+  UInt32 got = 0;
+  while (got < length) {
+
+    NSUInteger avail = _readBuffer.length - _readOffset;
+    if (avail == 0) {
+      if (![self readFrame:error]) {
+        return 0;
+      }
+      avail = _readBuffer.length;
     }
 
-    /* Cast should be safe:
-     * Have verified headerValue non-negative and of lesser or equal bitwidth to size_t. */
-    size_t frameSize = (size_t)headerValue;
-    [self ensureReadBufferHasLength:frameSize];
+    NSRange range;
+    range.location = _readOffset;
+    range.length = MIN(length - got, avail);
+
+    [_readBuffer getBytes:outBuffer+outBufferOffset+got range:range];
+    _readOffset += range.length;
+    got += range.length;
+  }
 
-    [mTransport readAll:[readBuffer mutableBytes] offset:0 length:frameSize];
+  return got;
 }
 
-- (void)ensureReadBufferHasLength:(size_t)length
+-(BOOL) readFrame:(NSError **)error
 {
-    if (readBuffer == nil) {
-        readBuffer = [[NSMutableData alloc] initWithLength:length];
-    } else {
-        size_t currentLength = [readBuffer length];
-        BOOL isTooLong = (currentLength >= length);
-        if (isTooLong) {
-            [readBuffer setLength:length];
-        } else {
-            size_t lengthToAdd = length - currentLength;
-            [readBuffer increaseLengthBy:lengthToAdd];
-        }
+  UInt8 i32rd[HEADER_SIZE];
+  if (![_transport readAll:i32rd offset:0 length:HEADER_SIZE error:error]) {
+    return NO;
+  }
+
+  SInt32 size =
+    ((i32rd[0] & 0xff) << 24) |
+    ((i32rd[1] & 0xff) << 16) |
+    ((i32rd[2] & 0xff) <<  8) |
+    ((i32rd[3] & 0xff));
+
+  if (_readBuffer == nil) {
+
+    _readBuffer = [NSMutableData dataWithLength:size];
+
+  }
+  else {
+
+    SInt32 len = (SInt32)_readBuffer.length;
+    if (len >= size) {
+
+      _readBuffer.length = size;
+
+    }
+    else {
+
+      // increase length of data buffer
+      [_readBuffer increaseLengthBy:size-len];
+
     }
+
+  }
+
+  // copy into internal memory buffer
+  if (![_transport readAll:_readBuffer.mutableBytes offset:0 length:size error:error]) {
+    return NO;
+  }
+
+  return YES;
 }
 
 @end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/THTTPClient.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/THTTPClient.h b/lib/cocoa/src/transport/THTTPClient.h
deleted file mode 100644
index 78935fb..0000000
--- a/lib/cocoa/src/transport/THTTPClient.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#import <Foundation/Foundation.h>
-#import "TTransport.h"
-
-@interface THTTPClient : NSObject <TTransport> {
-  NSURL * mURL;
-  NSMutableURLRequest * mRequest;
-  NSMutableData * mRequestData;
-  NSData * mResponseData;
-  size_t mResponseDataOffset;
-  NSString * mUserAgent;
-  int mTimeout;
-}
-
-- (id) initWithURL: (NSURL *) aURL;
-
-- (id) initWithURL: (NSURL *) aURL
-         userAgent: (NSString *) userAgent
-           timeout: (int) timeout;
-
-- (void) setURL: (NSURL *) aURL;
-
-@end
-

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/THTTPClient.m
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/THTTPClient.m b/lib/cocoa/src/transport/THTTPClient.m
deleted file mode 100644
index 169927c..0000000
--- a/lib/cocoa/src/transport/THTTPClient.m
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#import "THTTPClient.h"
-#import "TTransportException.h"
-#import "TObjective-C.h"
-
-@implementation THTTPClient
-
-
-- (void) setupRequest
-{
-  if (mRequest != nil) {
-    [mRequest release_stub];
-  }
-
-  // set up our request object that we'll use for each request
-  mRequest = [[NSMutableURLRequest alloc] initWithURL: mURL];
-  [mRequest setHTTPMethod: @"POST"];
-  [mRequest setValue: @"application/x-thrift" forHTTPHeaderField: @"Content-Type"];
-  [mRequest setValue: @"application/x-thrift" forHTTPHeaderField: @"Accept"];
-
-  NSString * userAgent = mUserAgent;
-  if (!userAgent) {
-    userAgent = @"Cocoa/THTTPClient";
-  }
-  [mRequest setValue: userAgent forHTTPHeaderField: @"User-Agent"];
-
-  [mRequest setCachePolicy: NSURLRequestReloadIgnoringCacheData];
-  if (mTimeout) {
-    [mRequest setTimeoutInterval: mTimeout];
-  }
-}
-
-
-- (id) initWithURL: (NSURL *) aURL
-{
-  return [self initWithURL: aURL
-                 userAgent: nil
-                   timeout: 0];
-}
-
-
-- (id) initWithURL: (NSURL *) aURL
-         userAgent: (NSString *) userAgent
-           timeout: (int) timeout
-{
-  self = [super init];
-  if (!self) {
-    return nil;
-  }
-
-  mTimeout = timeout;
-  if (userAgent) {
-    mUserAgent = [userAgent retain_stub];
-  }
-  mURL = [aURL retain_stub];
-
-  [self setupRequest];
-
-  // create our request data buffer
-  mRequestData = [[NSMutableData alloc] initWithCapacity: 1024];
-
-  return self;
-}
-
-
-- (void) setURL: (NSURL *) aURL
-{
-  [aURL retain_stub];
-  [mURL release_stub];
-  mURL = aURL;
-
-  [self setupRequest];
-}
-
-
-- (void) dealloc
-{
-  [mURL release_stub];
-  [mUserAgent release_stub];
-  [mRequest release_stub];
-  [mRequestData release_stub];
-  [mResponseData release_stub];
-  [super dealloc_stub];
-}
-
-
-- (size_t) readAll: (uint8_t *) buf offset: (size_t) offset length: (size_t) length
-{
-  NSRange r;
-  r.location = mResponseDataOffset;
-  r.length = length;
-
-  [mResponseData getBytes: buf+offset range: r];
-  mResponseDataOffset += length;
-
-  return length;
-}
-
-
-- (void) write: (const uint8_t *) data offset: (size_t) offset length: (size_t) length
-{
-  [mRequestData appendBytes: data+offset length: length];
-}
-
-
-- (void) flush
-{
-  [mRequest setHTTPBody: mRequestData]; // not sure if it copies the data
-
-  // make the HTTP request
-  NSURLResponse * response;
-  NSError * error;
-  NSData * responseData =
-    [NSURLConnection sendSynchronousRequest: mRequest returningResponse: &response error: &error];
-
-  [mRequestData setLength: 0];
-
-  if (responseData == nil) {
-    @throw [TTransportException exceptionWithName: @"TTransportException"
-                                reason: @"Could not make HTTP request"
-                                error: error];
-  }
-  if (![response isKindOfClass: [NSHTTPURLResponse class]]) {
-    @throw [TTransportException exceptionWithName: @"TTransportException"
-                                           reason: [NSString stringWithFormat: @"Unexpected NSURLResponse type: %@",
-                                                    NSStringFromClass([response class])]];
-  }
-
-  NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse *) response;
-  if ([httpResponse statusCode] != 200) {
-    @throw [TTransportException exceptionWithName: @"TTransportException"
-                                           reason: [NSString stringWithFormat: @"Bad response from HTTP server: %ld",
-                                                    (long)[httpResponse statusCode]]];
-  }
-
-  // phew!
-  [mResponseData release_stub];
-  mResponseData = [responseData retain_stub];
-  mResponseDataOffset = 0;
-}
-
-
-@end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/THTTPSessionTransport.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/THTTPSessionTransport.h b/lib/cocoa/src/transport/THTTPSessionTransport.h
new file mode 100644
index 0000000..003499b
--- /dev/null
+++ b/lib/cocoa/src/transport/THTTPSessionTransport.h
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#import <Foundation/Foundation.h>
+#import "TAsyncTransport.h"
+
+NS_ASSUME_NONNULL_BEGIN
+
+
+typedef NSError *__nullable (^THTTPSessionTransportResponseValidateBlock) (NSHTTPURLResponse *response, NSData *responseData);
+
+
+@interface THTTPSessionTransportFactory : NSObject<TAsyncTransportFactory>
+
+@property (strong, nonatomic) THTTPSessionTransportResponseValidateBlock responseValidate;
+
++(void) setupDefaultsForSessionConfiguration:(NSURLSessionConfiguration *)config
+                            withProtocolName:(NSString *)protocolName;
+
+-(id) initWithSession:(NSURLSession *)session
+                  URL:(NSURL *)aURL;
+
+@end
+
+
+@interface THTTPSessionTransport : NSObject <TAsyncTransport>
+
+@end
+
+
+NS_ASSUME_NONNULL_END

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/THTTPSessionTransport.m
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/THTTPSessionTransport.m b/lib/cocoa/src/transport/THTTPSessionTransport.m
new file mode 100644
index 0000000..c10b7fc
--- /dev/null
+++ b/lib/cocoa/src/transport/THTTPSessionTransport.m
@@ -0,0 +1,268 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#import "THTTPSessionTransport.h"
+#import "TTransportError.h"
+
+
+@interface THTTPSessionTransportFactory ()
+
+@property (strong, nonatomic) NSURLSession *session;
+@property (strong, nonatomic) NSURL *url;
+
+@end
+
+
+@interface THTTPSessionTransport ()
+
+@property (strong, nonatomic) THTTPSessionTransportFactory *factory;
+@property (strong, nonatomic) NSMutableData *requestData;
+@property (strong, nonatomic) NSData *responseData;
+@property (assign, nonatomic) NSUInteger responseDataOffset;
+
+-(instancetype) initWithFactory:(THTTPSessionTransportFactory *)factory;
+
+@end
+
+
+@implementation THTTPSessionTransportFactory
+
++(void) setupDefaultsForSessionConfiguration:(NSURLSessionConfiguration *)config withProtocolName:(NSString *)protocolName
+{
+  NSString *thriftContentType = @"application/x-thrift";
+  if (protocolName.length) {
+    thriftContentType = [thriftContentType stringByAppendingFormat:@"; p=%@", protocolName];
+  }
+
+  config.requestCachePolicy = NSURLRequestReloadIgnoringCacheData;
+  config.HTTPShouldUsePipelining = YES;
+  config.HTTPShouldSetCookies = NO;
+  config.URLCache = nil;
+  config.HTTPAdditionalHeaders = @{@"Content-Type":thriftContentType,
+                                   @"Accept":thriftContentType,
+                                   @"User-Agent":@"Thrift/Cocoa (Session)"};
+}
+
+
+-(id) initWithSession:(NSURLSession *)session URL:(NSURL *)url
+{
+  self = [super init];
+  if (self) {
+    _session = session;
+    _url = url;
+  }
+
+  return self;
+}
+
+-(id<TAsyncTransport>) newTransport
+{
+  return [[THTTPSessionTransport alloc] initWithFactory:self];
+}
+
+-(NSURLSessionDataTask *) taskWithRequest:(NSURLRequest *)request
+                        completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler
+                                    error:(NSError *__autoreleasing *)error
+{
+  NSURLSessionDataTask *newTask = [_session dataTaskWithRequest:request completionHandler:completionHandler];
+  if (!newTask) {
+    if (error) {
+      *error = [NSError errorWithDomain:TTransportErrorDomain
+                                   code:TTransportErrorUnknown
+                               userInfo:@{NSLocalizedDescriptionKey:@"Failed to create session data task"}];
+    }
+    return nil;
+  }
+
+  return newTask;
+}
+
+-(NSError *) validateResponse:(NSHTTPURLResponse *)response data:(NSData *)data
+{
+  if (_responseValidate) {
+    return _responseValidate(response, data);
+  }
+  return nil;
+}
+
+@end
+
+
+
+@implementation THTTPSessionTransport
+
+-(instancetype) initWithFactory:(THTTPSessionTransportFactory *)factory
+{
+  self = [super init];
+  if (self) {
+    _factory = factory;
+  }
+  return self;
+}
+
+-(BOOL) readAll:(UInt8 *)outBuffer offset:(UInt32)outBufferOffset length:(UInt32)length error:(NSError *__autoreleasing *)error
+{
+  UInt32 got = [self readAvail:outBuffer offset:outBufferOffset maxLength:length error:error];
+  if (got != length) {
+
+    // Report underflow only if readAvail didn't report error already
+    if (error && !*error) {
+      *error = [NSError errorWithDomain:TTransportErrorDomain
+                                   code:TTransportErrorEndOfFile
+                               userInfo:nil];
+    }
+
+    return NO;
+  }
+
+  return YES;
+}
+
+-(UInt32) readAvail:(UInt8 *)outBuffer offset:(UInt32)outBufferOffset maxLength:(UInt32)maxLength error:(NSError *__autoreleasing *)error
+{
+  NSUInteger avail = _responseData.length - _responseDataOffset;
+
+  NSRange range;
+  range.location = _responseDataOffset;
+  range.length = MIN(maxLength, avail);
+
+  [_responseData getBytes:outBuffer+outBufferOffset range:range];
+  _responseDataOffset += range.length;
+
+  return (UInt32)range.length;
+}
+
+-(BOOL) write:(const UInt8 *)data offset:(UInt32)offset length:(UInt32)length error:(NSError *__autoreleasing *)error
+{
+  if (!_requestData) {
+    _requestData = [NSMutableData dataWithCapacity:256];
+  }
+
+  [_requestData appendBytes:data+offset length:length];
+
+  return YES;
+}
+
+-(void) flushWithCompletion:(TAsyncCompletionBlock)completed failure:(TAsyncFailureBlock)failure
+{
+  NSError *error;
+
+  NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:_factory.url];
+  request.HTTPMethod = @"POST";
+  request.HTTPBody = _requestData;
+
+  _requestData = nil;
+
+  NSURLSessionDataTask *task = [_factory taskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
+
+    // Check response type
+    if (!error && ![response isKindOfClass:NSHTTPURLResponse.class]) {
+
+      error = [NSError errorWithDomain:TTransportErrorDomain
+                                   code:TTransportErrorUnknown
+                               userInfo:@{TTransportErrorHttpErrorKey: @(THttpTransportErrorInvalidResponse)}];
+
+    }
+
+    // Check status code
+    NSHTTPURLResponse *httpResponse = (id)response;
+    if (!error && httpResponse.statusCode != 200) {
+
+      THttpTransportError code;
+      if (httpResponse.statusCode == 401) {
+        code = THttpTransportErrorAuthentication;
+      }
+      else {
+        code = THttpTransportErrorInvalidStatus;
+      }
+
+      error = [NSError errorWithDomain:TTransportErrorDomain
+                                  code:TTransportErrorUnknown
+                              userInfo:@{TTransportErrorHttpErrorKey: @(code),
+                                         @"statusCode":@(httpResponse.statusCode)}];
+    }
+
+    // Allow factory to check
+    if (!error) {
+      error = [_factory validateResponse:httpResponse data:data];
+    }
+
+    _responseDataOffset = 0;
+
+    if (error) {
+
+      _responseData = nil;
+
+      failure(error);
+
+    }
+    else {
+
+      if (data == nil) {
+        data = [NSData data];
+      }
+
+      _responseData = data;
+
+      completed(self);
+    }
+
+  } error:&error];
+
+  if (!task) {
+    failure(error);
+    return;
+  }
+
+  [task resume];
+}
+
+-(BOOL) flush:(NSError *__autoreleasing *)error
+{
+  dispatch_semaphore_t completed = dispatch_semaphore_create(0);
+
+  __block BOOL result;
+  __block NSError *internalError;
+
+  [self flushWithCompletion:^(id < TAsyncTransport > transport) {
+
+    result = YES;
+
+    dispatch_semaphore_signal(completed);
+
+  } failure:^(NSError *error) {
+
+    internalError = error;
+
+    result = NO;
+
+    dispatch_semaphore_signal(completed);
+
+  }];
+
+  dispatch_semaphore_wait(completed, DISPATCH_TIME_FOREVER);
+
+  if (error) {
+    *error = internalError;
+  }
+
+  return result;
+}
+
+@end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/THTTPTransport.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/THTTPTransport.h b/lib/cocoa/src/transport/THTTPTransport.h
new file mode 100644
index 0000000..3c35daf
--- /dev/null
+++ b/lib/cocoa/src/transport/THTTPTransport.h
@@ -0,0 +1,39 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#import <Foundation/Foundation.h>
+#import "TTransport.h"
+
+NS_ASSUME_NONNULL_BEGIN
+
+
+@interface THTTPTransport : NSObject <TTransport>
+
+-(id) initWithURL:(NSURL *)aURL;
+
+-(id) initWithURL:(NSURL *)aURL
+        userAgent:(nullable NSString *)userAgent
+          timeout:(int)timeout;
+
+-(void) setURL:(NSURL *)aURL;
+
+@end
+
+
+NS_ASSUME_NONNULL_END

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/THTTPTransport.m
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/THTTPTransport.m b/lib/cocoa/src/transport/THTTPTransport.m
new file mode 100644
index 0000000..e4046c6
--- /dev/null
+++ b/lib/cocoa/src/transport/THTTPTransport.m
@@ -0,0 +1,182 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#import "THTTPTransport.h"
+#import "TTransportError.h"
+
+
+@interface THTTPTransport ()
+
+@property (strong, nonatomic) NSURL *url;
+@property (strong, nonatomic) NSMutableURLRequest *request;
+@property (strong, nonatomic) NSMutableData *requestData;
+@property (strong, nonatomic) NSData *responseData;
+@property (assign, nonatomic) NSUInteger responseDataOffset;
+@property (strong, nonatomic) NSString *userAgent;
+@property (assign, nonatomic) NSTimeInterval timeout;
+
+@end
+
+
+@implementation THTTPTransport
+
+-(void) setupRequest
+{
+  // set up our request object that we'll use for each request
+  _request = [[NSMutableURLRequest alloc] initWithURL:_url];
+  [_request setHTTPMethod:@"POST"];
+  [_request setValue:@"application/x-thrift" forHTTPHeaderField:@"Content-Type"];
+  [_request setValue:@"application/x-thrift" forHTTPHeaderField:@"Accept"];
+
+  NSString *userAgent = _userAgent;
+  if (!userAgent) {
+    userAgent = @"Thrift/Cocoa";
+  }
+  [_request setValue:userAgent forHTTPHeaderField:@"User-Agent"];
+
+  [_request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
+  if (_timeout) {
+    [_request setTimeoutInterval:_timeout];
+  }
+}
+
+
+-(id) initWithURL:(NSURL *)aURL
+{
+  return [self initWithURL:aURL
+                 userAgent:nil
+                   timeout:0];
+}
+
+
+-(id) initWithURL:(NSURL *)aURL
+        userAgent:(NSString *)aUserAgent
+          timeout:(int)aTimeout
+{
+  self = [super init];
+  if (!self) {
+    return nil;
+  }
+
+  _timeout = aTimeout;
+  _userAgent = aUserAgent;
+  _url = aURL;
+
+  [self setupRequest];
+
+  // create our request data buffer
+  _requestData = [[NSMutableData alloc] initWithCapacity:1024];
+
+  return self;
+}
+
+-(void) setURL:(NSURL *)aURL
+{
+  _url = aURL;
+
+  [self setupRequest];
+}
+
+-(BOOL) readAll:(UInt8 *)outBuffer offset:(UInt32)outBufferOffset length:(UInt32)length error:(NSError *__autoreleasing *)error
+{
+  UInt32 got = [self readAvail:outBuffer offset:outBufferOffset maxLength:length error:error];
+  if (got != length) {
+
+    // Report underflow only if readAvail didn't report error already
+    if (error && !*error) {
+      *error = [NSError errorWithDomain:TTransportErrorDomain
+                                   code:TTransportErrorEndOfFile
+                               userInfo:nil];
+    }
+
+    return NO;
+  }
+
+  return YES;
+}
+
+-(UInt32) readAvail:(UInt8 *)outBuffer offset:(UInt32)outBufferOffset maxLength:(UInt32)maxLength error:(NSError *__autoreleasing *)error
+{
+  NSUInteger avail = _responseData.length - _responseDataOffset;
+
+  NSRange range;
+  range.location = _responseDataOffset;
+  range.length = MIN(maxLength, avail);
+
+  [_responseData getBytes:outBuffer+outBufferOffset range:range];
+  _responseDataOffset += range.length;
+
+  return (UInt32)range.length;
+}
+
+-(BOOL) write:(const UInt8 *)data offset:(UInt32)offset length:(UInt32)length error:(NSError *__autoreleasing *)error
+{
+  [_requestData appendBytes:data+offset length:length];
+
+  return YES;
+}
+
+-(BOOL) flush:(NSError *__autoreleasing *)error
+{
+  [_request setHTTPBody:_requestData];
+
+  _responseDataOffset = 0;
+
+  // make the HTTP request
+  NSURLResponse *response;
+  _responseData = [NSURLConnection sendSynchronousRequest:_request returningResponse:&response error:error];
+  if (!_responseData) {
+    return NO;
+  }
+
+  [_requestData setLength:0];
+
+  if (![response isKindOfClass:NSHTTPURLResponse.class]) {
+    if (error) {
+      *error = [NSError errorWithDomain:TTransportErrorDomain
+                                   code:TTransportErrorUnknown
+                               userInfo:@{TTransportErrorHttpErrorKey: @(THttpTransportErrorInvalidResponse)}];
+    }
+    return NO;
+  }
+
+  NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
+  if ([httpResponse statusCode] != 200) {
+    if (error) {
+
+      THttpTransportError code;
+      if (httpResponse.statusCode == 401) {
+        code = THttpTransportErrorAuthentication;
+      }
+      else {
+        code = THttpTransportErrorInvalidStatus;
+      }
+
+      *error = [NSError errorWithDomain:TTransportErrorDomain
+                                   code:TTransportErrorUnknown
+                               userInfo:@{TTransportErrorHttpErrorKey: @(code),
+                                          @"statusCode":@(httpResponse.statusCode)}];
+    }
+    return NO;
+  }
+
+  return YES;
+}
+
+@end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/TMemoryBuffer.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/TMemoryBuffer.h b/lib/cocoa/src/transport/TMemoryBuffer.h
index fa4d371..6249d32 100644
--- a/lib/cocoa/src/transport/TMemoryBuffer.h
+++ b/lib/cocoa/src/transport/TMemoryBuffer.h
@@ -20,10 +20,18 @@
 #import <Foundation/Foundation.h>
 #import "TTransport.h"
 
-@interface TMemoryBuffer : NSObject <TTransport> {
-	NSMutableData *mBuffer;
-	NSUInteger mOffset;
-}
-- (id)initWithData:(NSData *)data;
-- (NSData *)getBuffer;
+NS_ASSUME_NONNULL_BEGIN
+
+
+@interface TMemoryBuffer : NSObject <TTransport>
+
+-(NSData *) buffer;
+
+-(id) initWithData:(NSData *)data;
+
+-(id) initWithDataNoCopy:(NSMutableData *)data;
+
 @end
+
+
+NS_ASSUME_NONNULL_END

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/TMemoryBuffer.m
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/TMemoryBuffer.m b/lib/cocoa/src/transport/TMemoryBuffer.m
index 4513ab8..ec19cc8 100644
--- a/lib/cocoa/src/transport/TMemoryBuffer.m
+++ b/lib/cocoa/src/transport/TMemoryBuffer.m
@@ -18,57 +18,104 @@
  */
 
 #import "TMemoryBuffer.h"
-#import "TTransportException.h"
-#import "TObjective-C.h"
+#import "TTransportError.h"
+
 
 #define GARBAGE_BUFFER_SIZE 4096 // 4KiB
 
+
+@interface TMemoryBuffer ()
+
+@property(strong, nonatomic) NSMutableData *buffer;
+@property(assign, nonatomic) UInt32 bufferOffset;
+
+@end
+
+
 @implementation TMemoryBuffer
-- (id)init {
-	if ((self = [super init])) {
-		mBuffer = [[NSMutableData alloc] init];
-		mOffset = 0;
-	}
-	return self;
+
+-(id) init
+{
+  if ((self = [super init])) {
+    _buffer = [NSMutableData new];
+    _bufferOffset = 0;
+  }
+  return self;
 }
 
-- (id)initWithData:(NSData *)data {
-	if ((self = [super init])) {
-		mBuffer = [data mutableCopy];
-		mOffset = 0;
-	}
-	return self;
+-(id) initWithData:(NSData *)data
+{
+  if (self = [super init]) {
+    _buffer = [data mutableCopy];
+    _bufferOffset = 0;
+  }
+  return self;
 }
 
-- (size_t) readAll: (uint8_t *) buf offset: (size_t) offset length: (size_t) length
+-(id) initWithDataNoCopy:(NSMutableData *)data
 {
-	if ([mBuffer length] - mOffset < length) {
-		@throw [TTransportException exceptionWithReason:@"Not enough bytes remain in buffer"];
-	}
-	[mBuffer getBytes:buf range:NSMakeRange(mOffset, length)];
-	mOffset += length;
-	if (mOffset >= GARBAGE_BUFFER_SIZE) {
-		[mBuffer replaceBytesInRange:NSMakeRange(0, mOffset) withBytes:NULL length:0];
-		mOffset = 0;
-	}
-	return length;
+  if (self = [super init]) {
+    _buffer = data;
+    _bufferOffset = 0;
+  }
+  return self;
 }
 
-- (void) write: (const uint8_t *) data offset: (size_t) offset length: (size_t) length
+-(BOOL) readAll:(UInt8 *)outBuffer offset:(UInt32)outBufferOffset length:(UInt32)length error:(NSError *__autoreleasing *)error
 {
-	[mBuffer appendBytes:data+offset length:length];
+  UInt32 got = [self readAvail:outBuffer offset:outBufferOffset maxLength:length error:error];
+  if (got != length) {
+
+    // Report underflow only if readAvail didn't report error already
+    if (error && !*error) {
+      *error = [NSError errorWithDomain:TTransportErrorDomain
+                                   code:TTransportErrorEndOfFile
+                               userInfo:nil];
+    }
+
+    return NO;
+  }
+
+  return YES;
 }
 
-- (void)flush {
-	// noop
+-(UInt32) readAvail:(UInt8 *)outBuffer offset:(UInt32)outBufferOffset maxLength:(UInt32)maxLength error:(NSError *__autoreleasing *)error
+{
+  UInt32 avail = (UInt32)_buffer.length - _bufferOffset;
+  if (avail == 0) {
+    return 0;
+  }
+
+  NSRange range;
+  range.location = _bufferOffset;
+  range.length = MIN(maxLength, avail);
+
+  [_buffer getBytes:outBuffer + outBufferOffset range:range];
+  _bufferOffset += range.length;
+
+  if (_bufferOffset >= GARBAGE_BUFFER_SIZE) {
+    [_buffer replaceBytesInRange:NSMakeRange(0, _bufferOffset) withBytes:NULL length:0];
+    _bufferOffset = 0;
+  }
+
+  return (UInt32)range.length;
+}
+
+-(BOOL) write:(const UInt8 *)inBuffer offset:(UInt32)inBufferOffset length:(UInt32)length error:(NSError *__autoreleasing *)error
+{
+  [_buffer appendBytes:inBuffer + inBufferOffset length:length];
+
+  return YES;
 }
 
-- (NSData *)getBuffer {
-	return [[mBuffer copy] autorelease_stub];
+-(NSData *) buffer
+{
+  return _buffer;
 }
 
-- (void)dealloc {
-	[mBuffer release_stub];
-	[super dealloc_stub];
+-(BOOL) flush:(NSError *__autoreleasing *)error
+{
+  return YES;
 }
+
 @end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/TNSFileHandleTransport.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/TNSFileHandleTransport.h b/lib/cocoa/src/transport/TNSFileHandleTransport.h
index ba2a209..db6edf3 100644
--- a/lib/cocoa/src/transport/TNSFileHandleTransport.h
+++ b/lib/cocoa/src/transport/TNSFileHandleTransport.h
@@ -21,15 +21,18 @@
 #import <Foundation/Foundation.h>
 #import "TTransport.h"
 
-@interface TNSFileHandleTransport : NSObject <TTransport> {
-  NSFileHandle * mInputFileHandle;
-  NSFileHandle * mOutputFileHandle;
-}
+NS_ASSUME_NONNULL_BEGIN
 
-- (id) initWithFileHandle: (NSFileHandle *) fileHandle;
 
-- (id) initWithInputFileHandle: (NSFileHandle *) inputFileHandle
-              outputFileHandle: (NSFileHandle *) outputFileHandle;
+@interface TNSFileHandleTransport : NSObject <TTransport>
+
+-(id) initWithFileHandle:(NSFileHandle *)fileHandle;
+
+-(id) initWithInputFileHandle:(NSFileHandle *)inputFileHandle
+             outputFileHandle:(NSFileHandle *)outputFileHandle;
 
 
 @end
+
+
+NS_ASSUME_NONNULL_END

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/TNSFileHandleTransport.m
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/TNSFileHandleTransport.m b/lib/cocoa/src/transport/TNSFileHandleTransport.m
index c2b18ca..c907f87 100644
--- a/lib/cocoa/src/transport/TNSFileHandleTransport.m
+++ b/lib/cocoa/src/transport/TNSFileHandleTransport.m
@@ -19,75 +19,100 @@
 
 
 #import "TNSFileHandleTransport.h"
-#import "TTransportException.h"
-#import "TObjective-C.h"
+#import "TTransportError.h"
+
+
+@interface TNSFileHandleTransport ()
+
+@property(strong, nonatomic) NSFileHandle *inputFileHandle;
+@property(strong, nonatomic) NSFileHandle *outputFileHandle;
+
+@end
 
 
 @implementation TNSFileHandleTransport
 
-- (id) initWithFileHandle: (NSFileHandle *) fileHandle
+-(id) initWithFileHandle:(NSFileHandle *)fileHandle
 {
-  return [self initWithInputFileHandle: fileHandle
-                      outputFileHandle: fileHandle];
+  return [self initWithInputFileHandle:fileHandle
+                      outputFileHandle:fileHandle];
 }
 
 
-- (id) initWithInputFileHandle: (NSFileHandle *) inputFileHandle
-              outputFileHandle: (NSFileHandle *) outputFileHandle
+-(id) initWithInputFileHandle:(NSFileHandle *)aInputFileHandle
+             outputFileHandle:(NSFileHandle *)aOutputFileHandle
 {
   self = [super init];
-
-  mInputFileHandle = [inputFileHandle retain_stub];
-  mOutputFileHandle = [outputFileHandle retain_stub];
-
+  if (self) {
+    _inputFileHandle = aInputFileHandle;
+    _outputFileHandle = aOutputFileHandle;
+  }
   return self;
 }
 
 
-- (void) dealloc {
-  [mInputFileHandle release_stub];
-  [mOutputFileHandle release_stub];
-  [super dealloc_stub];
+-(BOOL) readAll:(UInt8 *)buf offset:(UInt32)off length:(UInt32)len error:(NSError *__autoreleasing *)error
+{
+  UInt32 got = 0;
+  while (got < len) {
+
+    NSData *d = [_inputFileHandle readDataOfLength:len-got];
+    if (d.length == 0) {
+      if (error) {
+        *error = [NSError errorWithDomain:TTransportErrorDomain
+                                     code:TTransportErrorEndOfFile
+                                 userInfo:nil];
+      }
+      return NO;
+    }
+
+    [d getBytes:buf+got length:d.length];
+    got += d.length;
+  }
+  return YES;
 }
 
 
-- (size_t) readAll: (uint8_t *) buf offset: (size_t) offset length: (size_t) length
+-(UInt32) readAvail:(UInt8 *)buf offset:(UInt32)off maxLength:(UInt32)len error:(NSError *__autoreleasing *)error
 {
-  size_t totalBytesRead = 0;
-  while (totalBytesRead < length) {
-    NSData * data = [mInputFileHandle readDataOfLength: length-totalBytesRead];
-    if ([data length] == 0) {
-      @throw [TTransportException exceptionWithName: @"TTransportException"
-                                  reason: @"Cannot read. No more data."];
+  UInt32 got = 0;
+  while (got < len) {
+
+    NSData *d = [_inputFileHandle readDataOfLength:len-got];
+    if (d.length == 0) {
+      break;
     }
-    [data getBytes: buf+totalBytesRead];
-    totalBytesRead += [data length];
+
+    [d getBytes:buf+got length:d.length];
+    got += d.length;
   }
-  return totalBytesRead;
+  return got;
 }
 
 
-- (void) write: (const uint8_t *) data offset: (size_t) offset length: (size_t) length
+-(BOOL) write:(const UInt8 *)data offset:(UInt32)offset length:(UInt32)length error:(NSError *__autoreleasing *)error
 {
-  const void *pos = data + offset;
-  NSData * dataObject = [[NSData alloc] initWithBytesNoCopy: (void *)pos
-                                                     length: length
-                                               freeWhenDone: NO];
+  void *pos = (void *)data + offset;
 
   @try {
-    [mOutputFileHandle writeData: dataObject];
-  } @catch (NSException * e) {
-    @throw [TTransportException exceptionWithName: @"TTransportException"
-                                           reason: [NSString stringWithFormat: @"%s: Unable to write data: %@", __PRETTY_FUNCTION__, e]];
+    [_outputFileHandle writeData:[NSData dataWithBytesNoCopy:pos length:length freeWhenDone:NO]];
+  }
+  @catch (NSException *e) {
+    if (error) {
+      *error = [NSError errorWithDomain:TTransportErrorDomain
+                                   code:TTransportErrorNotOpen
+                               userInfo:@{}];
+    }
+    return NO;
   }
 
-  [dataObject release_stub];
+  return YES;
 }
 
 
-- (void) flush
+-(BOOL) flush:(NSError *__autoreleasing *)error
 {
-
+  return YES;
 }
 
 @end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/TNSStreamTransport.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/TNSStreamTransport.h b/lib/cocoa/src/transport/TNSStreamTransport.h
index 8011fb9..54c4884 100644
--- a/lib/cocoa/src/transport/TNSStreamTransport.h
+++ b/lib/cocoa/src/transport/TNSStreamTransport.h
@@ -20,21 +20,24 @@
 #import <Foundation/Foundation.h>
 #import "TTransport.h"
 
-@interface TNSStreamTransport : NSObject <TTransport> {
+NS_ASSUME_NONNULL_BEGIN
 
-}
 
-@property (nonatomic, strong) NSInputStream * mInput;
-@property (nonatomic, strong) NSOutputStream * mOutput;
+@interface TNSStreamTransport : NSObject <TTransport>
 
-- (id) initWithInputStream: (NSInputStream *) input
-              outputStream: (NSOutputStream *) output;
+@property (strong, nonatomic) NSInputStream *input;
+@property (strong, nonatomic) NSOutputStream *output;
 
-- (id) initWithInputStream: (NSInputStream *) input;
+-(id) initWithInputStream:(nullable NSInputStream *)input
+             outputStream:(nullable NSOutputStream *)output;
 
-- (id) initWithOutputStream: (NSOutputStream *) output;
+-(id) initWithInputStream:(NSInputStream *)input;
 
-@end
+-(id) initWithOutputStream:(NSOutputStream *)output;
+
+-(void) close;
 
+@end
 
 
+NS_ASSUME_NONNULL_END

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/TNSStreamTransport.m
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/TNSStreamTransport.m b/lib/cocoa/src/transport/TNSStreamTransport.m
index 7ac1cdc..c425043 100644
--- a/lib/cocoa/src/transport/TNSStreamTransport.m
+++ b/lib/cocoa/src/transport/TNSStreamTransport.m
@@ -18,79 +18,136 @@
  */
 
 #import "TNSStreamTransport.h"
-#import "TTransportException.h"
-#import "TObjective-C.h"
+#import "TTransportError.h"
+
+
+@interface TNSStreamTransport ()
+@end
 
 
 @implementation TNSStreamTransport
 
-- (id) initWithInputStream: (NSInputStream *) input
-              outputStream: (NSOutputStream *) output
+-(id) initWithInputStream:(NSInputStream *)input
+             outputStream:(NSOutputStream *)output
 {
   self = [super init];
-  self.mInput = [input retain_stub];
-  self.mOutput = [output retain_stub];
+  if (self) {
+    _input = input;
+    _output = output;
+  }
   return self;
 }
 
-- (id) initWithInputStream: (NSInputStream *) input
+-(id) initWithInputStream:(NSInputStream *)input
 {
-  return [self initWithInputStream: input outputStream: nil];
+  return [self initWithInputStream:input outputStream:nil];
 }
 
-- (id) initWithOutputStream: (NSOutputStream *) output
+-(id) initWithOutputStream:(NSOutputStream *)output
 {
-  return [self initWithInputStream: nil outputStream: output];
+  return [self initWithInputStream:nil outputStream:output];
 }
 
-- (void) dealloc
+-(void) dealloc
 {
-  [self.mInput release_stub];
-  [self.mOutput release_stub];
-  [super dealloc_stub];
+  [self close];
 }
 
+-(BOOL) readAll:(UInt8 *)buf offset:(UInt32)off length:(UInt32)len error:(NSError *__autoreleasing *)error
+{
+  UInt32 got = 0;
+  while (got < len) {
+
+    UInt32 read = (UInt32)[_input read:buf+off+got maxLength:len-got];
+    if (read <= 0) {
+      if (error) {
+        *error = [NSError errorWithDomain:TTransportErrorDomain
+                                     code:TTransportErrorNotOpen
+                                 userInfo:@{}];
+      }
+      return NO;
+    }
 
-- (size_t) readAll: (uint8_t *) buf offset: (size_t) offset length: (size_t) length
+    got += read;
+  }
+
+  return YES;
+}
+
+
+-(UInt32) readAvail:(UInt8 *)buf offset:(UInt32)off maxLength:(UInt32)len error:(NSError *__autoreleasing *)error
 {
-  size_t totalBytesRead = 0;
-  ssize_t bytesRead = 0;
-  while (totalBytesRead < length) {
-    bytesRead = [self.mInput read: buf+offset+totalBytesRead maxLength: length-totalBytesRead];
-
-    BOOL encounteredErrorOrEOF = (bytesRead <= 0);
-    if (encounteredErrorOrEOF) {
-      @throw [TTransportException exceptionWithReason: @"Cannot read. Remote side has closed."];
-    } else {
-        /* bytesRead is guaranteed to be positive and within the range representable by size_t. */
-        totalBytesRead += (size_t)bytesRead;
+  UInt32 got = 0;
+  while (got < len) {
+
+    UInt32 read = (UInt32)[_input read:buf+off+got maxLength:len-got];
+    if (read <= 0) {
+      break;
     }
+
+    got += read;
   }
-  return totalBytesRead;
+
+  return got;
 }
 
 
-- (void) write: (const uint8_t *) data offset: (size_t) offset length: (size_t) length
+-(BOOL) write:(const UInt8 *)data offset:(UInt32)offset length:(UInt32)length error:(NSError *__autoreleasing *)error
 {
-  size_t totalBytesWritten = 0;
-  ssize_t bytesWritten = 0;
-  while (totalBytesWritten < length) {
-    bytesWritten = [self.mOutput write: data+offset+totalBytesWritten maxLength: length-totalBytesWritten];
-    if (bytesWritten < 0) {
-      @throw [TTransportException exceptionWithReason: @"Error writing to transport output stream."
-                                                error: [self.mOutput streamError]];
-    } else if (bytesWritten == 0) {
-      @throw [TTransportException exceptionWithReason: @"End of output stream."];
-    } else {
-        /* bytesWritten is guaranteed to be positive and within the range representable by size_t. */
-        totalBytesWritten += (size_t)bytesWritten;
+  int got = 0;
+  NSInteger total = 0;
+  while (got < length) {
+
+    total = [_output write:data+offset+got maxLength:length-got];
+    if (total == -1) {
+      if (error) {
+        *error = [NSError errorWithDomain:TTransportErrorDomain
+                                     code:TTransportErrorNotOpen
+                                 userInfo:@{}];
+      }
+      return NO;
     }
+    else if (total == 0) {
+      if (error) {
+        *error = [NSError errorWithDomain:TTransportErrorDomain
+                                     code:TTransportErrorEndOfFile
+                                 userInfo:@{}];
+      }
+      return NO;
+    }
+
+    got += total;
   }
+
+  return YES;
 }
 
-- (void) flush
+-(BOOL) flush:(NSError *__autoreleasing *)error
 {
-  // no flush for you!
+  return YES;
+}
+
+-(void) close
+{
+  NSInputStream *input = self.input;
+  if (input) {
+    // Close and reset inputstream
+    CFReadStreamSetProperty((__bridge CFReadStreamRef)(input), kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
+    [input setDelegate:nil];
+    [input close];
+    [input removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
+    input = nil;
+  }
+
+  NSOutputStream *output = self.output;
+  if (output) {
+    // Close and reset outputstream
+    CFWriteStreamSetProperty((__bridge CFWriteStreamRef)(output), kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
+    [output setDelegate:nil];
+    [output close];
+    [output removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
+    output = nil;
+  }
 }
 
 @end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/TSSLSocketClient.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/TSSLSocketClient.h b/lib/cocoa/src/transport/TSSLSocketClient.h
deleted file mode 100644
index 44de124..0000000
--- a/lib/cocoa/src/transport/TSSLSocketClient.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#import <Foundation/Foundation.h>
-#import "TNSStreamTransport.h"
-
-@interface TSSLSocketClient : TNSStreamTransport
-#if TARGET_OS_IPHONE || (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6)
-<NSStreamDelegate>
-#endif
-{
-    NSInputStream *inputStream;
-    NSOutputStream *outputStream;
-@private
-    NSString *sslHostname;
-    int sd;
-}
-
-- (id) initWithHostname: (NSString *) hostname
-                   port: (int) port;
-
-- (BOOL) isOpen;
-
-@end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/TSSLSocketClient.m
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/TSSLSocketClient.m b/lib/cocoa/src/transport/TSSLSocketClient.m
deleted file mode 100644
index d8c55d6..0000000
--- a/lib/cocoa/src/transport/TSSLSocketClient.m
+++ /dev/null
@@ -1,261 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-#import <Foundation/Foundation.h>
-#import <CoreFoundation/CoreFoundation.h>
-#import "TSSLSocketClient.h"
-#import "TSSLSocketException.h"
-#import "TObjective-C.h"
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <netdb.h>
-
-#if !TARGET_OS_IPHONE
-#import <CoreServices/CoreServices.h>
-#else
-#import <CFNetwork/CFNetwork.h>
-#endif
-
-@implementation TSSLSocketClient
-
-- (id) initWithHostname: (NSString *) hostname
-                   port: (int) port
-{
-    sslHostname = hostname;
-	CFReadStreamRef readStream = NULL;
-	CFWriteStreamRef writeStream = NULL;
-    
-    
-    /* create a socket structure */
-    struct sockaddr_in pin;
-    struct hostent *hp = NULL;
-    for(int i = 0; i < 10; i++) {
-        
-
-        
-        if ((hp = gethostbyname([hostname UTF8String])) == NULL) { 
-            NSLog(@"failed to resolve hostname %@", hostname);
-            herror("resolv");
-            if(i == 9) {
-                @throw [TSSLSocketException exceptionWithReason: @"failed to resolve hostname"];
-            }
-            [NSThread sleepForTimeInterval:0.2];
-        } else {
-            break;
-        }
-    }
-
-    memset (&pin, 0, sizeof(pin));
-    pin.sin_family = AF_INET;
-    memcpy(&pin.sin_addr, hp->h_addr, sizeof(struct in_addr));
-    pin.sin_port = htons (port);
-    
-    /* create the socket */
-    if ((sd = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
-    {
-        NSLog(@"failed to create socket for host %@:%d", hostname, port);
-        @throw [TSSLSocketException exceptionWithReason: @"failed to create socket"];
-    }
-    
-    /* open a connection */
-    if (connect (sd, (struct sockaddr *) &pin, sizeof(pin)) == -1)
-    {
-        NSLog(@"failed to create conenct to host %@:%d", hostname, port);
-        @throw [TSSLSocketException exceptionWithReason: @"failed to connect"];
-    }
-    CFStreamCreatePairWithSocket(kCFAllocatorDefault, sd, &readStream, &writeStream);
-    
-    CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
-    CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
-    
-	if (readStream && writeStream) {
-        CFReadStreamSetProperty(readStream,
-                                kCFStreamPropertySocketSecurityLevel,
-                                kCFStreamSocketSecurityLevelTLSv1);
-        
-        NSDictionary *settings =
-        [NSDictionary dictionaryWithObjectsAndKeys:
-         (id)kCFBooleanTrue, (id)kCFStreamSSLValidatesCertificateChain,
-         nil];
-        
-        CFReadStreamSetProperty((CFReadStreamRef)readStream,
-                                kCFStreamPropertySSLSettings,
-                                (CFTypeRef)settings);
-        CFWriteStreamSetProperty((CFWriteStreamRef)writeStream,
-                                 kCFStreamPropertySSLSettings,
-                                 (CFTypeRef)settings);
-        
-		inputStream = (bridge_stub NSInputStream *)readStream;
-		[inputStream retain_stub];
-		[inputStream setDelegate:self];
-   		[inputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
-		[inputStream open];
-		
-		outputStream = (bridge_stub NSOutputStream *)writeStream;
-		[outputStream retain_stub];
-		[outputStream setDelegate:self];
-        [outputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
-		[outputStream open];
-        
-        
-        CFRelease(readStream);
-        CFRelease(writeStream);
-	}
-    
-    
-	
-	self = [super initWithInputStream: inputStream outputStream: outputStream];
-    
-	return self;
-}
-
-#pragma mark -
-#pragma mark NSStreamDelegate
-- (void)stream:(NSStream *)aStream
-    handleEvent:(NSStreamEvent)eventCode {
-    switch (eventCode) {
-        case NSStreamEventNone:
-            break;
-        case NSStreamEventHasBytesAvailable:
-            break;
-        case NSStreamEventOpenCompleted:
-            break;
-        case NSStreamEventHasSpaceAvailable:
-        {
-            SecPolicyRef policy = SecPolicyCreateSSL(NO, (__bridge CFStringRef)(sslHostname));
-            SecTrustRef trust = NULL;
-            CFArrayRef streamCertificatesRef =
-            CFBridgingRetain((__bridge id)((__bridge CFArrayRef)([aStream propertyForKey:(NSString *) kCFStreamPropertySSLPeerCertificates])));
-            SecTrustCreateWithCertificates(CFBridgingRetain((__bridge id)(streamCertificatesRef)),
-                                           policy,
-                                           &trust);
-            
-            SecTrustResultType trustResultType = kSecTrustResultInvalid;
-            SecTrustEvaluate(trust, &trustResultType);
-            
-            BOOL proceed = NO;
-            switch (trustResultType) {
-                case kSecTrustResultProceed:
-                    proceed = YES;
-                    break;
-                case kSecTrustResultUnspecified:
-                    NSLog(@"Trusted by OS");
-                    proceed = YES;
-                    break;
-                case kSecTrustResultRecoverableTrustFailure:
-                    proceed = recoverFromTrustFailure(trust);
-                    break;
-                case kSecTrustResultDeny:
-                    NSLog(@"Deny");
-                    break;
-                case kSecTrustResultFatalTrustFailure:
-                    NSLog(@"FatalTrustFailure");
-                    break;
-                case kSecTrustResultOtherError:
-                    NSLog(@"OtherError");
-                    break;
-                case kSecTrustResultInvalid:
-                    NSLog(@"Invalid");
-                    break;
-                default:
-                    NSLog(@"Default");
-                    break;
-            }
-            
-            if (trust) {
-                CFRelease(trust);
-            }
-            if (policy) {
-                CFRelease(policy);
-            }
-            if (!proceed) {
-                NSLog(@"Cannot trust certificate. TrustResultType: %u", trustResultType);
-                [aStream close];
-                @throw [TSSLSocketException exceptionWithReason: @"Cannot trust certificate"];
-            }
-        }
-            break;
-        case NSStreamEventErrorOccurred:
-        {
-            NSError *theError = [aStream streamError];
-            NSLog(@"Error occurred opening stream: %@", theError);
-//            @throw [TSSLSocketException exceptionWithReason: @"Error occurred opening stream" error: theError];
-            break;
-        }
-        case NSStreamEventEndEncountered:
-            break;
-    }
-}
-
-bool recoverFromTrustFailure(SecTrustRef myTrust)
-{
-    
-    SecTrustResultType trustResult;
-    OSStatus status = SecTrustEvaluate(myTrust, &trustResult);
-    
-    CFAbsoluteTime trustTime,currentTime,timeIncrement,newTime;
-    CFDateRef newDate;
-    if (trustResult == kSecTrustResultRecoverableTrustFailure) {
-        trustTime = SecTrustGetVerifyTime(myTrust);
-        timeIncrement = 31536000;
-        currentTime = CFAbsoluteTimeGetCurrent();
-        newTime = currentTime - timeIncrement;
-        if (trustTime - newTime){
-            newDate = CFDateCreate(NULL, newTime);
-            SecTrustSetVerifyDate(myTrust, newDate);
-            status = SecTrustEvaluate(myTrust, &trustResult);
-        }
-    }
-    if (trustResult != kSecTrustResultProceed) {
-        NSLog(@"Certificate trust failure");
-        return false;
-    }
-    return true;
-}
-
-- (void)close
-{
-    if(self.mInput) {
-        //Close and reset inputstream
-        CFReadStreamSetProperty((__bridge CFReadStreamRef)(self.mInput), kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
-        [self.mInput setDelegate:nil];
-        [self.mInput close];
-        [self.mInput removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
-        self.mInput = nil;
-    }
-    
-    if(self.mOutput) {
-        //Close and reset outputstream
-        CFReadStreamSetProperty((__bridge CFReadStreamRef)(self.mOutput), kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
-        [self.mOutput setDelegate:nil];
-        [self.mOutput close];
-        [self.mOutput removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
-        self.mOutput = nil;
-    }
-}
-
-- (BOOL) isOpen
-{
-    if(sd > 0)
-        return TRUE;
-    else
-        return FALSE;
-}
-
-@end
-

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/TSSLSocketException.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/TSSLSocketException.h b/lib/cocoa/src/transport/TSSLSocketException.h
deleted file mode 100644
index c290b05..0000000
--- a/lib/cocoa/src/transport/TSSLSocketException.h
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#import "TTransportException.h"
-
-@interface TSSLSocketException : TTransportException
-
-+ (id) exceptionWithReason: (NSString *) reason
-                     error: (NSError *) error;
-
-+ (id) exceptionWithReason: (NSString *) reason;
-
-@end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/TSSLSocketException.m
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/TSSLSocketException.m b/lib/cocoa/src/transport/TSSLSocketException.m
deleted file mode 100644
index 99eadf5..0000000
--- a/lib/cocoa/src/transport/TSSLSocketException.m
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#import "TSSLSocketException.h"
-
-@implementation TSSLSocketException
-
-+ (id) exceptionWithReason: (NSString *) reason
-                     error: (NSError *) error
-{
-    NSDictionary * userInfo = nil;
-    if (error != nil) {
-        userInfo = [NSDictionary dictionaryWithObject: error forKey: @"error"];
-    }
-    
-    return [super exceptionWithName: @"TSSLSocketException"
-                             reason: reason
-                           userInfo: userInfo];
-}
-
-+ (id) exceptionWithReason: (NSString *) reason
-{
-    return [self exceptionWithReason: reason error: nil];
-}
-
-@end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/TSSLSocketTransport.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/TSSLSocketTransport.h b/lib/cocoa/src/transport/TSSLSocketTransport.h
new file mode 100644
index 0000000..b606c4a
--- /dev/null
+++ b/lib/cocoa/src/transport/TSSLSocketTransport.h
@@ -0,0 +1,37 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#import <Foundation/Foundation.h>
+#import "TNSStreamTransport.h"
+
+NS_ASSUME_NONNULL_BEGIN
+
+
+@interface TSSLSocketTransport : TNSStreamTransport <NSStreamDelegate>
+
+-(id) initWithHostname:(NSString *)hostname
+                  port:(int)port
+                 error:(NSError **)error;
+
+-(BOOL) isOpen;
+
+@end
+
+
+NS_ASSUME_NONNULL_END

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/TSSLSocketTransport.m
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/TSSLSocketTransport.m b/lib/cocoa/src/transport/TSSLSocketTransport.m
new file mode 100644
index 0000000..ab5eb3d
--- /dev/null
+++ b/lib/cocoa/src/transport/TSSLSocketTransport.m
@@ -0,0 +1,304 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#import <Foundation/Foundation.h>
+#import <CoreFoundation/CoreFoundation.h>
+#import "TSSLSocketTransport.h"
+#import "TSSLSocketTransportError.h"
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <netdb.h>
+
+#if !TARGET_OS_IPHONE
+#import <CoreServices/CoreServices.h>
+#else
+#import <CFNetwork/CFNetwork.h>
+#endif
+
+@interface TSSLSocketTransport ()
+
+@property(strong, nonatomic) NSString *sslHostname;
+@property(assign, nonatomic) int sd;
+
+@end
+
+
+@implementation TSSLSocketTransport
+
+-(id) initWithHostname:(NSString *)hostname
+                  port:(int)port
+                 error:(NSError **)error
+{
+  _sslHostname = hostname;
+  CFReadStreamRef readStream = NULL;
+  CFWriteStreamRef writeStream = NULL;
+
+
+  /* create a socket structure */
+  struct sockaddr_in pin;
+  struct hostent *hp = NULL;
+  for (int i = 0; i < 10; i++) {
+
+
+
+    if ((hp = gethostbyname([hostname UTF8String])) == NULL) {
+      NSLog(@"failed to resolve hostname %@", hostname);
+      herror("resolv");
+      if (i == 9) {
+        if (error) {
+          *error = [NSError errorWithDomain:TSSLSocketTransportErrorDomain
+                                       code:TSSLSocketTransportErrorHostanameResolution
+                                   userInfo:nil];
+        }
+        return nil;
+      }
+      [NSThread sleepForTimeInterval:0.2];
+    }
+    else {
+      break;
+    }
+  }
+
+  memset(&pin, 0, sizeof(pin));
+  pin.sin_family = AF_INET;
+  memcpy(&pin.sin_addr, hp->h_addr, sizeof(struct in_addr));
+  pin.sin_port = htons(port);
+
+  /* create the socket */
+  if ((_sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) {
+    NSLog(@"failed to create socket for host %@:%d", hostname, port);
+    if (error) {
+      *error = [NSError errorWithDomain:TSSLSocketTransportErrorDomain
+                                   code:TSSLSocketTransportErrorSocketCreate
+                               userInfo:nil];
+    }
+    return nil;
+  }
+
+  /* open a connection */
+  if (connect(_sd, (struct sockaddr *)&pin, sizeof(pin)) == -1) {
+    NSLog(@"failed to create conenct to host %@:%d", hostname, port);
+    if (error) {
+      *error = [NSError errorWithDomain:TSSLSocketTransportErrorDomain
+                                   code:TSSLSocketTransportErrorConnect
+                               userInfo:nil];
+    }
+    return nil;
+  }
+  CFStreamCreatePairWithSocket(kCFAllocatorDefault, _sd, &readStream, &writeStream);
+
+  CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
+  CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
+
+  NSInputStream *inputStream;
+  NSOutputStream *outputStream;
+
+  if (readStream && writeStream) {
+
+    CFReadStreamSetProperty(readStream,
+                            kCFStreamPropertySocketSecurityLevel,
+                            kCFStreamSocketSecurityLevelTLSv1);
+
+    NSDictionary *settings = @{(__bridge NSString *)kCFStreamSSLValidatesCertificateChain: @YES};
+
+    CFReadStreamSetProperty((CFReadStreamRef)readStream,
+                            kCFStreamPropertySSLSettings,
+                            (CFTypeRef)settings);
+
+    CFWriteStreamSetProperty((CFWriteStreamRef)writeStream,
+                             kCFStreamPropertySSLSettings,
+                             (CFTypeRef)settings);
+
+    inputStream = (__bridge NSInputStream *)readStream;
+    [inputStream setDelegate:self];
+    [inputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
+    [inputStream open];
+
+    outputStream = (__bridge NSOutputStream *)writeStream;
+    [outputStream setDelegate:self];
+    [outputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
+    [outputStream open];
+
+    CFRelease(readStream);
+    CFRelease(writeStream);
+  }
+
+  self = [super initWithInputStream:inputStream outputStream:outputStream];
+
+  return self;
+}
+
+-(void) dealloc
+{
+  [self close];
+}
+
+#pragma mark -
+#pragma mark NSStreamDelegate
+
+-(void) stream:(NSStream *)aStream
+   handleEvent:(NSStreamEvent)eventCode
+{
+  switch (eventCode) {
+  case NSStreamEventNone:
+    break;
+
+  case NSStreamEventHasBytesAvailable:
+    break;
+
+  case NSStreamEventOpenCompleted:
+    break;
+
+  case NSStreamEventHasSpaceAvailable: {
+
+    BOOL proceed = NO;
+    SecTrustResultType trustResult = kSecTrustResultInvalid;
+    CFMutableArrayRef newPolicies = NULL;
+
+    do {
+
+      SecTrustRef trust = (__bridge SecTrustRef)[aStream propertyForKey:(NSString *)kCFStreamPropertySSLPeerTrust];
+
+      // Add new policy to current list of policies
+      SecPolicyRef policy = SecPolicyCreateSSL(NO, (__bridge CFStringRef)(_sslHostname));
+      if (!policy) {
+        break;
+      }
+
+      CFArrayRef policies;
+      if (SecTrustCopyPolicies(trust, &policies) != errSecSuccess) {
+        CFRelease(policy);
+        break;
+      }
+
+      newPolicies = CFArrayCreateMutableCopy(NULL, 0, policies);
+      CFArrayAppendValue(newPolicies, policy);
+
+      CFRelease(policies);
+      CFRelease(policy);
+
+      // Update trust policies
+      if (SecTrustSetPolicies(trust, newPolicies) != errSecSuccess) {
+        break;
+      }
+
+      // Evaluate the trust chain
+      if (SecTrustEvaluate(trust, &trustResult) != errSecSuccess) {
+        break;
+      }
+
+      switch (trustResult) {
+      case kSecTrustResultProceed:
+        // NSLog(@"Trusted by USER");
+        proceed = YES;
+        break;
+
+      case kSecTrustResultUnspecified:
+        // NSLog(@"Trusted by OS");
+        proceed = YES;
+        break;
+
+      case kSecTrustResultRecoverableTrustFailure:
+        proceed = recoverFromTrustFailure(trust, trustResult);
+        break;
+
+      case kSecTrustResultDeny:
+        // NSLog(@"Deny");
+        break;
+
+      case kSecTrustResultFatalTrustFailure:
+        // NSLog(@"FatalTrustFailure");
+        break;
+
+      case kSecTrustResultOtherError:
+        // NSLog(@"OtherError");
+        break;
+
+      case kSecTrustResultInvalid:
+        // NSLog(@"Invalid");
+        break;
+
+      default:
+        // NSLog(@"Default");
+        break;
+      }
+
+    }
+    while (NO);
+
+    if (!proceed) {
+      NSLog(@"TSSLSocketTransport: Cannot trust certificate. Result: %u", trustResult);
+      [aStream close];
+    }
+
+    if (newPolicies) {
+      CFRelease(newPolicies);
+    }
+
+  }
+  break;
+
+  case NSStreamEventErrorOccurred: {
+    NSLog(@"TSSLSocketTransport: Error occurred opening stream: %@", [aStream streamError]);
+    break;
+  }
+
+  case NSStreamEventEndEncountered:
+    break;
+  }
+}
+
+BOOL recoverFromTrustFailure(SecTrustRef myTrust, SecTrustResultType lastTrustResult)
+{
+  CFAbsoluteTime trustTime = SecTrustGetVerifyTime(myTrust);
+  CFAbsoluteTime currentTime = CFAbsoluteTimeGetCurrent();
+
+  CFAbsoluteTime timeIncrement = 31536000;
+  CFAbsoluteTime newTime = currentTime - timeIncrement;
+
+  if (trustTime - newTime) {
+
+    CFDateRef newDate = CFDateCreate(NULL, newTime);
+    SecTrustSetVerifyDate(myTrust, newDate);
+    CFRelease(newDate);
+
+    if (SecTrustEvaluate(myTrust, &lastTrustResult) != errSecSuccess) {
+      return NO;
+    }
+
+  }
+
+  if (lastTrustResult == kSecTrustResultProceed || lastTrustResult == kSecTrustResultUnspecified) {
+    return YES;
+  }
+
+  NSLog(@"TSSLSocketTransport: Unable to recover certificate trust failure");
+  return YES;
+}
+
+-(BOOL) isOpen
+{
+  if (_sd > 0) {
+    return TRUE;
+  }
+  else {
+    return FALSE;
+  }
+}
+
+@end

http://git-wip-us.apache.org/repos/asf/thrift/blob/56e5b9b0/lib/cocoa/src/transport/TSSLSocketTransportError.h
----------------------------------------------------------------------
diff --git a/lib/cocoa/src/transport/TSSLSocketTransportError.h b/lib/cocoa/src/transport/TSSLSocketTransportError.h
new file mode 100644
index 0000000..e17f39e
--- /dev/null
+++ b/lib/cocoa/src/transport/TSSLSocketTransportError.h
@@ -0,0 +1,30 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#import "TTransportError.h"
+
+
+extern NSString *TSSLSocketTransportErrorDomain;
+
+
+typedef NS_ENUM (int, TSSLSocketTransportError) {
+  TSSLSocketTransportErrorHostanameResolution  = -10000,
+  TSSLSocketTransportErrorSocketCreate         = -10001,
+  TSSLSocketTransportErrorConnect              = -10002,
+};