Merge branch 'aputinski-swift3' into swift3

* aputinski-swift3:
  update tests, add test for base64
  Fix Xcode 8 Beta 3 issues/warnings
  Use Legacy Swift Language Version
  Enable APPLICATION_EXTENSION_API_ONLY
This commit is contained in:
Erik 2016-07-20 11:08:00 -04:00
commit 8df6eeb85a
No known key found for this signature in database
GPG Key ID: 4930B7C5FBC1A69D
13 changed files with 83 additions and 61 deletions

View File

@ -846,6 +846,7 @@
isa = XCBuildConfiguration; isa = XCBuildConfiguration;
buildSettings = { buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO; ALWAYS_SEARCH_USER_PATHS = NO;
APPLICATION_EXTENSION_API_ONLY = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++"; CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_MODULES = YES;
@ -892,6 +893,7 @@
SDKROOT = iphoneos; SDKROOT = iphoneos;
SKIP_INSTALL = YES; SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 3.0;
TARGETED_DEVICE_FAMILY = "1,2"; TARGETED_DEVICE_FAMILY = "1,2";
VERSIONING_SYSTEM = "apple-generic"; VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = ""; VERSION_INFO_PREFIX = "";
@ -902,6 +904,7 @@
isa = XCBuildConfiguration; isa = XCBuildConfiguration;
buildSettings = { buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO; ALWAYS_SEARCH_USER_PATHS = NO;
APPLICATION_EXTENSION_API_ONLY = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++"; CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_MODULES = YES;
@ -941,6 +944,7 @@
PRODUCT_BUNDLE_IDENTIFIER = io.socket.SocketIOClientSwift; PRODUCT_BUNDLE_IDENTIFIER = io.socket.SocketIOClientSwift;
SDKROOT = iphoneos; SDKROOT = iphoneos;
SKIP_INSTALL = YES; SKIP_INSTALL = YES;
SWIFT_VERSION = 3.0;
TARGETED_DEVICE_FAMILY = "1,2"; TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES; VALIDATE_PRODUCT = YES;
VERSIONING_SYSTEM = "apple-generic"; VERSIONING_SYSTEM = "apple-generic";

View File

@ -13,14 +13,14 @@ class SocketAckManagerTest: XCTestCase {
var ackManager = SocketAckManager() var ackManager = SocketAckManager()
func testAddAcks() { func testAddAcks() {
let callbackExpection = self.expectation(withDescription: "callbackExpection") let callbackExpection = self.expectation(description: "callbackExpection")
let itemsArray = ["Hi", "ho"] let itemsArray = ["Hi", "ho"]
func callback(_ items: [AnyObject]) { func callback(_ items: [AnyObject]) {
callbackExpection.fulfill() callbackExpection.fulfill()
} }
ackManager.addAck(1, callback: callback) ackManager.addAck(1, callback: callback)
ackManager.executeAck(1, with: itemsArray, onQueue: DispatchQueue.main) ackManager.executeAck(1, with: itemsArray, onQueue: DispatchQueue.main)
waitForExpectations(withTimeout: 3.0, handler: nil) waitForExpectations(timeout: 3.0, handler: nil)
} }
} }

View File

@ -154,8 +154,8 @@ class SocketBasicPacketTest: XCTestCase {
if case let .right(packet) = socket.parseString(engineString) { if case let .right(packet) = socket.parseString(engineString) {
var packet = packet var packet = packet
XCTAssertEqual(packet.event, "test") XCTAssertEqual(packet.event, "test")
packet.addData(data) _ = packet.addData(data)
packet.addData(data2) _ = packet.addData(data2)
XCTAssertEqual(packet.args[0] as? String, "~~0") XCTAssertEqual(packet.args[0] as? String, "~~0")
} else { } else {
XCTFail() XCTFail()

View File

@ -22,17 +22,17 @@ class SocketEngineTest: XCTestCase {
} }
func testBasicPollingMessage() { func testBasicPollingMessage() {
let expect = expectation(withDescription: "Basic polling test") let expect = expectation(description: "Basic polling test")
client.on("blankTest") {data, ack in client.on("blankTest") {data, ack in
expect.fulfill() expect.fulfill()
} }
engine.parsePollingMessage("15:42[\"blankTest\"]") engine.parsePollingMessage("15:42[\"blankTest\"]")
waitForExpectations(withTimeout: 3, handler: nil) waitForExpectations(timeout: 3, handler: nil)
} }
func testTwoPacketsInOnePollTest() { func testTwoPacketsInOnePollTest() {
let finalExpectation = expectation(withDescription: "Final packet in poll test") let finalExpectation = expectation(description: "Final packet in poll test")
var gotBlank = false var gotBlank = false
client.on("blankTest") {data, ack in client.on("blankTest") {data, ack in
@ -40,7 +40,7 @@ class SocketEngineTest: XCTestCase {
} }
client.on("stringTest") {data, ack in client.on("stringTest") {data, ack in
if let str = data[0] as? String where gotBlank { if let str = data[0] as? String, gotBlank {
if str == "hello" { if str == "hello" {
finalExpectation.fulfill() finalExpectation.fulfill()
} }
@ -48,35 +48,35 @@ class SocketEngineTest: XCTestCase {
} }
engine.parsePollingMessage("15:42[\"blankTest\"]24:42[\"stringTest\",\"hello\"]") engine.parsePollingMessage("15:42[\"blankTest\"]24:42[\"stringTest\",\"hello\"]")
waitForExpectations(withTimeout: 3, handler: nil) waitForExpectations(timeout: 3, handler: nil)
} }
func testEngineDoesErrorOnUnknownTransport() { func testEngineDoesErrorOnUnknownTransport() {
let finalExpectation = expectation(withDescription: "Unknown Transport") let finalExpectation = expectation(description: "Unknown Transport")
client.on("error") {data, ack in client.on("error") {data, ack in
if let error = data[0] as? String where error == "Unknown transport" { if let error = data[0] as? String, error == "Unknown transport" {
finalExpectation.fulfill() finalExpectation.fulfill()
} }
} }
engine.parseEngineMessage("{\"code\": 0, \"message\": \"Unknown transport\"}", fromPolling: false) engine.parseEngineMessage("{\"code\": 0, \"message\": \"Unknown transport\"}", fromPolling: false)
waitForExpectations(withTimeout: 3, handler: nil) waitForExpectations(timeout: 3, handler: nil)
} }
func testEngineDoesErrorOnUnknownMessage() { func testEngineDoesErrorOnUnknownMessage() {
let finalExpectation = expectation(withDescription: "Engine Errors") let finalExpectation = expectation(description: "Engine Errors")
client.on("error") {data, ack in client.on("error") {data, ack in
finalExpectation.fulfill() finalExpectation.fulfill()
} }
engine.parseEngineMessage("afafafda", fromPolling: false) engine.parseEngineMessage("afafafda", fromPolling: false)
waitForExpectations(withTimeout: 3, handler: nil) waitForExpectations(timeout: 3, handler: nil)
} }
func testEngineDecodesUTF8Properly() { func testEngineDecodesUTF8Properly() {
let expect = expectation(withDescription: "Engine Decodes utf8") let expect = expectation(description: "Engine Decodes utf8")
client.on("stringTest") {data, ack in client.on("stringTest") {data, ack in
XCTAssertEqual(data[0] as? String, "lïne one\nlīne \rtwo", "Failed string test") XCTAssertEqual(data[0] as? String, "lïne one\nlīne \rtwo", "Failed string test")
@ -84,7 +84,7 @@ class SocketEngineTest: XCTestCase {
} }
engine.parsePollingMessage("41:42[\"stringTest\",\"lïne one\\nlīne \\rtwo\"]") engine.parsePollingMessage("41:42[\"stringTest\",\"lïne one\\nlīne \\rtwo\"]")
waitForExpectations(withTimeout: 3, handler: nil) waitForExpectations(timeout: 3, handler: nil)
} }
func testEncodeURLProperly() { func testEncodeURLProperly() {
@ -102,4 +102,23 @@ class SocketEngineTest: XCTestCase {
XCTAssertEqual(engine.urlPolling.query, "transport=polling&b64=1&forbidden=%21%2A%27%28%29%3B%3A%40%26%3D%2B%24%2C%2F%3F%25%23%5B%5D%22%20%7B%7D") XCTAssertEqual(engine.urlPolling.query, "transport=polling&b64=1&forbidden=%21%2A%27%28%29%3B%3A%40%26%3D%2B%24%2C%2F%3F%25%23%5B%5D%22%20%7B%7D")
XCTAssertEqual(engine.urlWebSocket.query, "transport=websocket&forbidden=%21%2A%27%28%29%3B%3A%40%26%3D%2B%24%2C%2F%3F%25%23%5B%5D%22%20%7B%7D") XCTAssertEqual(engine.urlWebSocket.query, "transport=websocket&forbidden=%21%2A%27%28%29%3B%3A%40%26%3D%2B%24%2C%2F%3F%25%23%5B%5D%22%20%7B%7D")
} }
func testBase64Data() {
let expect = expectation(description: "Engine Decodes base64 data")
let b64String = "b4aGVsbG8NCg=="
let packetString = "451-[\"test\",{\"test\":{\"_placeholder\":true,\"num\":0}}]"
client.on("test") {data, ack in
if let data = data[0] as? Data, let string = String(data: data, encoding: .utf8) {
XCTAssertEqual(string, "hello")
}
expect.fulfill()
}
engine.parseEngineMessage(packetString, fromPolling: false)
engine.parseEngineMessage(b64String, fromPolling: false)
waitForExpectations(timeout: 3, handler: nil)
}
} }

View File

@ -136,7 +136,7 @@ class SocketParserTest: XCTestCase {
let keys = Array(SocketParserTest.packetTypes.keys) let keys = Array(SocketParserTest.packetTypes.keys)
measure { measure {
for item in keys.enumerated() { for item in keys.enumerated() {
self.testSocket.parseString(item.element) _ = self.testSocket.parseString(item.element)
} }
} }
} }

View File

@ -37,18 +37,18 @@ class SocketSideEffectTest: XCTestCase {
} }
func testHandleAck() { func testHandleAck() {
let expect = expectation(withDescription: "handled ack") let expect = expectation(description: "handled ack")
socket.emitWithAck("test")(timeoutAfter: 0) {data in socket.emitWithAck("test")(timeoutAfter: 0) {data in
XCTAssertEqual(data[0] as? String, "hello world") XCTAssertEqual(data[0] as? String, "hello world")
expect.fulfill() expect.fulfill()
} }
socket.parseSocketMessage("30[\"hello world\"]") socket.parseSocketMessage("30[\"hello world\"]")
waitForExpectations(withTimeout: 3, handler: nil) waitForExpectations(timeout: 3, handler: nil)
} }
func testHandleAck2() { func testHandleAck2() {
let expect = expectation(withDescription: "handled ack2") let expect = expectation(description: "handled ack2")
socket.emitWithAck("test")(timeoutAfter: 0) {data in socket.emitWithAck("test")(timeoutAfter: 0) {data in
XCTAssertTrue(data.count == 2, "Wrong number of ack items") XCTAssertTrue(data.count == 2, "Wrong number of ack items")
expect.fulfill() expect.fulfill()
@ -56,33 +56,33 @@ class SocketSideEffectTest: XCTestCase {
socket.parseSocketMessage("61-0[{\"_placeholder\":true,\"num\":0},{\"test\":true}]") socket.parseSocketMessage("61-0[{\"_placeholder\":true,\"num\":0},{\"test\":true}]")
socket.parseBinaryData(Data()) socket.parseBinaryData(Data())
waitForExpectations(withTimeout: 3, handler: nil) waitForExpectations(timeout: 3, handler: nil)
} }
func testHandleEvent() { func testHandleEvent() {
let expect = expectation(withDescription: "handled event") let expect = expectation(description: "handled event")
socket.on("test") {data, ack in socket.on("test") {data, ack in
XCTAssertEqual(data[0] as? String, "hello world") XCTAssertEqual(data[0] as? String, "hello world")
expect.fulfill() expect.fulfill()
} }
socket.parseSocketMessage("2[\"test\",\"hello world\"]") socket.parseSocketMessage("2[\"test\",\"hello world\"]")
waitForExpectations(withTimeout: 3, handler: nil) waitForExpectations(timeout: 3, handler: nil)
} }
func testHandleStringEventWithQuotes() { func testHandleStringEventWithQuotes() {
let expect = expectation(withDescription: "handled event") let expect = expectation(description: "handled event")
socket.on("test") {data, ack in socket.on("test") {data, ack in
XCTAssertEqual(data[0] as? String, "\"hello world\"") XCTAssertEqual(data[0] as? String, "\"hello world\"")
expect.fulfill() expect.fulfill()
} }
socket.parseSocketMessage("2[\"test\",\"\\\"hello world\\\"\"]") socket.parseSocketMessage("2[\"test\",\"\\\"hello world\\\"\"]")
waitForExpectations(withTimeout: 3, handler: nil) waitForExpectations(timeout: 3, handler: nil)
} }
func testHandleOnceEvent() { func testHandleOnceEvent() {
let expect = expectation(withDescription: "handled event") let expect = expectation(description: "handled event")
socket.once("test") {data, ack in socket.once("test") {data, ack in
XCTAssertEqual(data[0] as? String, "hello world") XCTAssertEqual(data[0] as? String, "hello world")
XCTAssertEqual(self.socket.testHandlers.count, 0) XCTAssertEqual(self.socket.testHandlers.count, 0)
@ -90,7 +90,7 @@ class SocketSideEffectTest: XCTestCase {
} }
socket.parseSocketMessage("2[\"test\",\"hello world\"]") socket.parseSocketMessage("2[\"test\",\"hello world\"]")
waitForExpectations(withTimeout: 3, handler: nil) waitForExpectations(timeout: 3, handler: nil)
} }
func testOffWithEvent() { func testOffWithEvent() {
@ -112,21 +112,21 @@ class SocketSideEffectTest: XCTestCase {
} }
func testHandlesErrorPacket() { func testHandlesErrorPacket() {
let expect = expectation(withDescription: "Handled error") let expect = expectation(description: "Handled error")
socket.on("error") {data, ack in socket.on("error") {data, ack in
if let error = data[0] as? String where error == "test error" { if let error = data[0] as? String, error == "test error" {
expect.fulfill() expect.fulfill()
} }
} }
socket.parseSocketMessage("4\"test error\"") socket.parseSocketMessage("4\"test error\"")
waitForExpectations(withTimeout: 3, handler: nil) waitForExpectations(timeout: 3, handler: nil)
} }
func testHandleBinaryEvent() { func testHandleBinaryEvent() {
let expect = expectation(withDescription: "handled binary event") let expect = expectation(description: "handled binary event")
socket.on("test") {data, ack in socket.on("test") {data, ack in
if let dict = data[0] as? NSDictionary, data = dict["test"] as? NSData { if let dict = data[0] as? NSDictionary, let data = dict["test"] as? NSData {
XCTAssertEqual(data, self.data) XCTAssertEqual(data, self.data)
expect.fulfill() expect.fulfill()
} }
@ -134,7 +134,7 @@ class SocketSideEffectTest: XCTestCase {
socket.parseSocketMessage("51-[\"test\",{\"test\":{\"_placeholder\":true,\"num\":0}}]") socket.parseSocketMessage("51-[\"test\",{\"test\":{\"_placeholder\":true,\"num\":0}}]")
socket.parseBinaryData(data) socket.parseBinaryData(data)
waitForExpectations(withTimeout: 3, handler: nil) waitForExpectations(timeout: 3, handler: nil)
} }
func testSocketDataToAnyObject() { func testSocketDataToAnyObject() {
@ -144,10 +144,10 @@ class SocketSideEffectTest: XCTestCase {
} }
func testHandleMultipleBinaryEvent() { func testHandleMultipleBinaryEvent() {
let expect = expectation(withDescription: "handled multiple binary event") let expect = expectation(description: "handled multiple binary event")
socket.on("test") {data, ack in socket.on("test") {data, ack in
if let dict = data[0] as? NSDictionary, data = dict["test"] as? NSData, if let dict = data[0] as? NSDictionary, let data = dict["test"] as? NSData,
data2 = dict["test2"] as? NSData { let data2 = dict["test2"] as? NSData {
XCTAssertEqual(data, self.data) XCTAssertEqual(data, self.data)
XCTAssertEqual(data2, self.data2) XCTAssertEqual(data2, self.data2)
expect.fulfill() expect.fulfill()
@ -157,7 +157,7 @@ class SocketSideEffectTest: XCTestCase {
socket.parseSocketMessage("52-[\"test\",{\"test\":{\"_placeholder\":true,\"num\":0},\"test2\":{\"_placeholder\":true,\"num\":1}}]") socket.parseSocketMessage("52-[\"test\",{\"test\":{\"_placeholder\":true,\"num\":0},\"test2\":{\"_placeholder\":true,\"num\":1}}]")
socket.parseBinaryData(data) socket.parseBinaryData(data)
socket.parseBinaryData(data2) socket.parseBinaryData(data2)
waitForExpectations(withTimeout: 3, handler: nil) waitForExpectations(timeout: 3, handler: nil)
} }
func testSocketManager() { func testSocketManager() {

View File

@ -151,8 +151,7 @@ public final class SocketEngine : NSObject, SocketEnginePollable, SocketEngineWe
if message.hasPrefix("b4") { if message.hasPrefix("b4") {
// binary in base64 string // binary in base64 string
let noPrefix = message[message.characters.index(message.startIndex, offsetBy: 2)..<message.endIndex] let noPrefix = message[message.characters.index(message.startIndex, offsetBy: 2)..<message.endIndex]
if let data = Data(base64Encoded: noPrefix, options: Data.Base64DecodingOptions(rawValue: 0)) {
if let data = Data(base64Encoded: noPrefix, options: Data.Base64EncodingOptions(rawValue: 0)) {
client?.parseEngineBinaryData(data) client?.parseEngineBinaryData(data)
} }
@ -372,7 +371,7 @@ public final class SocketEngine : NSObject, SocketEnginePollable, SocketEngineWe
upgradeWs = false upgradeWs = false
} }
if let pingInterval = json["pingInterval"] as? Double, pingTimeout = json["pingTimeout"] as? Double { if let pingInterval = json["pingInterval"] as? Double, let pingTimeout = json["pingTimeout"] as? Double {
self.pingInterval = pingInterval / 1000.0 self.pingInterval = pingInterval / 1000.0
self.pingTimeout = pingTimeout / 1000.0 self.pingTimeout = pingTimeout / 1000.0
} }

View File

@ -113,7 +113,7 @@ extension SocketEnginePollable {
func doLongPoll(for req: URLRequest) { func doLongPoll(for req: URLRequest) {
doRequest(for: req) {[weak self] data, res, err in doRequest(for: req) {[weak self] data, res, err in
guard let this = self where this.polling else { return } guard let this = self, this.polling else { return }
if err != nil || data == nil { if err != nil || data == nil {
DefaultSocketLogger.Logger.error(err?.localizedDescription ?? "Error", type: "SocketEnginePolling") DefaultSocketLogger.Logger.error(err?.localizedDescription ?? "Error", type: "SocketEnginePolling")

View File

@ -92,7 +92,7 @@ extension SocketEngineSpec {
func doubleEncodeUTF8(_ string: String) -> String { func doubleEncodeUTF8(_ string: String) -> String {
if let latin1 = string.data(using: String.Encoding.utf8), if let latin1 = string.data(using: String.Encoding.utf8),
utf8 = NSString(data: latin1, encoding: String.Encoding.isoLatin1.rawValue) { let utf8 = NSString(data: latin1, encoding: String.Encoding.isoLatin1.rawValue) {
return utf8 as String return utf8 as String
} else { } else {
return string return string
@ -101,7 +101,7 @@ extension SocketEngineSpec {
func fixDoubleUTF8(_ string: String) -> String { func fixDoubleUTF8(_ string: String) -> String {
if let utf8 = string.data(using: String.Encoding.isoLatin1), if let utf8 = string.data(using: String.Encoding.isoLatin1),
latin1 = NSString(data: utf8, encoding: String.Encoding.utf8.rawValue) { let latin1 = NSString(data: utf8, encoding: String.Encoding.utf8.rawValue) {
return latin1 as String return latin1 as String
} else { } else {
return string return string

View File

@ -150,7 +150,7 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
let time = DispatchTime.now() + Double(Int64(timeoutAfter) * Int64(NSEC_PER_SEC)) / Double(NSEC_PER_SEC) let time = DispatchTime.now() + Double(Int64(timeoutAfter) * Int64(NSEC_PER_SEC)) / Double(NSEC_PER_SEC)
handleQueue.after(when: time) {[weak self] in handleQueue.after(when: time) {[weak self] in
if let this = self where this.status != .connected && this.status != .disconnected { if let this = self, this.status != .connected && this.status != .disconnected {
this.status = .disconnected this.status = .disconnected
this.engine?.disconnect(reason: "Connect timeout") this.engine?.disconnect(reason: "Connect timeout")

View File

@ -217,7 +217,7 @@ extension NSDictionary {
var options = Set<SocketIOClientOption>() var options = Set<SocketIOClientOption>()
for (rawKey, value) in self { for (rawKey, value) in self {
if let key = rawKey as? String, opt = NSDictionary.keyValueToSocketIOClientOption(key, value: value) { if let key = rawKey as? String, let opt = NSDictionary.keyValueToSocketIOClientOption(key, value: value) {
options.insertIgnore(opt) options.insertIgnore(opt)
} }
} }

View File

@ -96,7 +96,7 @@ public class SSLSecurity : NSObject {
DispatchQueue.global(attributes: DispatchQueue.GlobalAttributes.qosDefault).async { DispatchQueue.global(attributes: DispatchQueue.GlobalAttributes.qosDefault).async {
let pubKeys = certs.reduce([SecKey]()) { (pubKeys: [SecKey], cert: SSLCert) -> [SecKey] in let pubKeys = certs.reduce([SecKey]()) { (pubKeys: [SecKey], cert: SSLCert) -> [SecKey] in
var pubKeys = pubKeys var pubKeys = pubKeys
if let data = cert.certData where cert.key == nil { if let data = cert.certData, cert.key == nil {
cert.key = self.extractPublicKey(data) cert.key = self.extractPublicKey(data)
} }
if let key = cert.key { if let key = cert.key {

View File

@ -305,7 +305,7 @@ public class WebSocket : NSObject, StreamDelegate {
} }
if let cipherSuites = self.enabledSSLCipherSuites { if let cipherSuites = self.enabledSSLCipherSuites {
if let sslContextIn = CFReadStreamCopyProperty(inputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext?, if let sslContextIn = CFReadStreamCopyProperty(inputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext?,
sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? { let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? {
let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count) let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count)
let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count) let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count)
if resIn != errSecSuccess { if resIn != errSecSuccess {
@ -349,7 +349,7 @@ public class WebSocket : NSObject, StreamDelegate {
//delegate for the stream methods. Processes incoming bytes //delegate for the stream methods. Processes incoming bytes
public func stream(_ aStream: Stream, handle eventCode: Stream.Event) { public func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
if let sec = security where !certValidated && [.hasBytesAvailable, .hasSpaceAvailable].contains(eventCode) { if let sec = security, !certValidated && [.hasBytesAvailable, .hasSpaceAvailable].contains(eventCode) {
let possibleTrust: AnyObject? = aStream.property(forKey: kCFStreamPropertySSLPeerTrust as Stream.PropertyKey) let possibleTrust: AnyObject? = aStream.property(forKey: kCFStreamPropertySSLPeerTrust as Stream.PropertyKey)
if let trust: AnyObject = possibleTrust { if let trust: AnyObject = possibleTrust {
let domain: AnyObject? = aStream.property(forKey: kCFStreamSSLPeerName as Stream.PropertyKey) let domain: AnyObject? = aStream.property(forKey: kCFStreamSSLPeerName as Stream.PropertyKey)
@ -534,7 +534,7 @@ public class WebSocket : NSObject, StreamDelegate {
} }
/// Process one message at the start of `buffer`. Return another buffer (sharing storage) that contains the leftover contents of `buffer` that I didn't process. /// Process one message at the start of `buffer`. Return another buffer (sharing storage) that contains the leftover contents of `buffer` that I didn't process.
@warn_unused_result
private func processOneRawMessage(inBuffer buffer: UnsafeBufferPointer<UInt8>) -> UnsafeBufferPointer<UInt8> { private func processOneRawMessage(inBuffer buffer: UnsafeBufferPointer<UInt8>) -> UnsafeBufferPointer<UInt8> {
let response = readStack.last let response = readStack.last
guard let baseAddress = buffer.baseAddress else { fatalError("") } guard let baseAddress = buffer.baseAddress else { fatalError("") }
@ -543,7 +543,7 @@ public class WebSocket : NSObject, StreamDelegate {
fragBuffer = Data(buffer: buffer) fragBuffer = Data(buffer: buffer)
return emptyBuffer return emptyBuffer
} }
if let response = response where response.bytesLeft > 0 { if let response = response, response.bytesLeft > 0 {
var len = response.bytesLeft var len = response.bytesLeft
var extra = bufferLen - response.bytesLeft var extra = bufferLen - response.bytesLeft
if response.bytesLeft > bufferLen { if response.bytesLeft > bufferLen {
@ -612,10 +612,10 @@ public class WebSocket : NSObject, StreamDelegate {
var dataLength = UInt64(payloadLen) var dataLength = UInt64(payloadLen)
if dataLength == 127 { if dataLength == 127 {
dataLength = WebSocket.readUint64(baseAddress, offset: offset) dataLength = WebSocket.readUint64(baseAddress, offset: offset)
offset += sizeof(UInt64) offset += sizeof(UInt64.self)
} else if dataLength == 126 { } else if dataLength == 126 {
dataLength = UInt64(WebSocket.readUint16(baseAddress, offset: offset)) dataLength = UInt64(WebSocket.readUint16(baseAddress, offset: offset))
offset += sizeof(UInt16) offset += sizeof(UInt16.self)
} }
if bufferLen < offset || UInt64(bufferLen - offset) < dataLength { if bufferLen < offset || UInt64(bufferLen - offset) < dataLength {
fragBuffer = Data(bytes: baseAddress, count: bufferLen) fragBuffer = Data(bytes: baseAddress, count: bufferLen)
@ -754,10 +754,10 @@ public class WebSocket : NSObject, StreamDelegate {
///write a an error to the socket ///write a an error to the socket
private func writeError(_ code: UInt16) { private func writeError(_ code: UInt16) {
let buf = NSMutableData(capacity: sizeof(UInt16)) let buf = NSMutableData(capacity: sizeof(UInt16.self))
let buffer = UnsafeMutablePointer<UInt8>(buf!.bytes) let buffer = UnsafeMutablePointer<UInt8>(buf!.bytes)
WebSocket.writeUint16(buffer, offset: 0, value: code) WebSocket.writeUint16(buffer, offset: 0, value: code)
dequeueWrite(Data(bytes: buffer, count: sizeof(UInt16)), code: .connectionClose) dequeueWrite(Data(bytes: buffer, count: sizeof(UInt16.self)), code: .connectionClose)
} }
///used to write things to the stream ///used to write things to the stream
private func dequeueWrite(_ data: Data, code: OpCode, writeCompletion: (() -> ())? = nil) { private func dequeueWrite(_ data: Data, code: OpCode, writeCompletion: (() -> ())? = nil) {
@ -775,19 +775,19 @@ public class WebSocket : NSObject, StreamDelegate {
} else if dataLength <= Int(UInt16.max) { } else if dataLength <= Int(UInt16.max) {
buffer[1] = 126 buffer[1] = 126
WebSocket.writeUint16(buffer, offset: offset, value: UInt16(dataLength)) WebSocket.writeUint16(buffer, offset: offset, value: UInt16(dataLength))
offset += sizeof(UInt16) offset += sizeof(UInt16.self)
} else { } else {
buffer[1] = 127 buffer[1] = 127
WebSocket.writeUint64(buffer, offset: offset, value: UInt64(dataLength)) WebSocket.writeUint64(buffer, offset: offset, value: UInt64(dataLength))
offset += sizeof(UInt64) offset += sizeof(UInt64.self)
} }
buffer[1] |= s.MaskMask buffer[1] |= s.MaskMask
let maskKey = UnsafeMutablePointer<UInt8>(buffer + offset) let maskKey = UnsafeMutablePointer<UInt8>(buffer + offset)
SecRandomCopyBytes(kSecRandomDefault, Int(sizeof(UInt32)), maskKey) _ = SecRandomCopyBytes(kSecRandomDefault, Int(sizeof(UInt32.self)), maskKey)
offset += sizeof(UInt32) offset += sizeof(UInt32.self)
for i in 0..<dataLength { for i in 0..<dataLength {
buffer[offset] = bytes[i] ^ maskKey[i % sizeof(UInt32)] buffer[offset] = bytes[i] ^ maskKey[i % sizeof(UInt32.self)]
offset += 1 offset += 1
} }
var total = 0 var total = 0
@ -809,8 +809,8 @@ public class WebSocket : NSObject, StreamDelegate {
total += len total += len
} }
if total >= offset { if total >= offset {
if let queue = self?.queue, callback = writeCompletion { if let queue = self?.queue, let callback = writeCompletion {
queue.asynchronously() { queue.async {
callback() callback()
} }
} }