untested with socket.io, this just compiles
This commit is contained in:
parent
58571e5387
commit
78727dc0ee
@ -88,7 +88,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
||||
case NOOP = 6
|
||||
|
||||
init?(str:String?) {
|
||||
if let value = str?.toInt(), raw = PacketType(rawValue: value) {
|
||||
if let value = Int(str ?? ""), raw = PacketType(rawValue: value) {
|
||||
self = raw
|
||||
} else {
|
||||
return nil
|
||||
@ -115,7 +115,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
||||
SocketLogger.log("Engine is being deinit", client: self)
|
||||
}
|
||||
|
||||
public func close(#fast:Bool) {
|
||||
public func close(fast fast:Bool) {
|
||||
SocketLogger.log("Engine is being closed. Fast: %@", client: self, args: fast)
|
||||
|
||||
pingTimer?.invalidate()
|
||||
@ -135,7 +135,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
||||
if websocket {
|
||||
var byteArray = [UInt8](count: 1, repeatedValue: 0x0)
|
||||
byteArray[0] = 4
|
||||
var mutData = NSMutableData(bytes: &byteArray, length: 1)
|
||||
let mutData = NSMutableData(bytes: &byteArray, length: 1)
|
||||
|
||||
mutData.appendData(data)
|
||||
|
||||
@ -156,7 +156,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
||||
|
||||
let path = socketPath == "" ? "/socket.io" : socketPath
|
||||
|
||||
var url = "\(client!.socketURL)\(path)/?transport="
|
||||
let url = "\(client!.socketURL)\(path)/?transport="
|
||||
var urlPolling:String
|
||||
var urlWebSocket:String
|
||||
|
||||
@ -243,18 +243,18 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
||||
|
||||
session.dataTaskWithRequest(req) {[weak self] data, res, err in
|
||||
if let this = self {
|
||||
if err != nil {
|
||||
if err != nil || data == nil {
|
||||
if this.polling {
|
||||
this.handlePollingFailed(err.localizedDescription)
|
||||
this.handlePollingFailed(err?.localizedDescription ?? "Error")
|
||||
} else {
|
||||
SocketLogger.err(err.localizedDescription, client: this)
|
||||
SocketLogger.err(err?.localizedDescription ?? "Error", client: this)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
SocketLogger.log("Got polling response", client: this)
|
||||
|
||||
if let str = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
|
||||
if let str = NSString(data: data!, encoding: NSUTF8StringEncoding) as? String {
|
||||
dispatch_async(this.parseQueue) {[weak this] in
|
||||
this?.parsePollingMessage(str)
|
||||
}
|
||||
@ -267,7 +267,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
||||
} else if !this.closed && this.polling {
|
||||
this.doPoll()
|
||||
}
|
||||
}}.resume()
|
||||
}}?.resume()
|
||||
}
|
||||
|
||||
private func flushProbeWait() {
|
||||
@ -299,7 +299,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
||||
var postStr = ""
|
||||
|
||||
for packet in postWait {
|
||||
let len = count(packet)
|
||||
let len = packet.characters.count
|
||||
|
||||
postStr += "\(len):\(packet)"
|
||||
}
|
||||
@ -329,10 +329,10 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
||||
session.dataTaskWithRequest(req) {[weak self] data, res, err in
|
||||
if let this = self {
|
||||
if err != nil && this.polling {
|
||||
this.handlePollingFailed(err.localizedDescription)
|
||||
this.handlePollingFailed(err?.localizedDescription ?? "Error")
|
||||
return
|
||||
} else if err != nil {
|
||||
NSLog(err.localizedDescription)
|
||||
NSLog(err?.localizedDescription ?? "Error")
|
||||
return
|
||||
}
|
||||
|
||||
@ -344,7 +344,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
||||
this?.doPoll()
|
||||
}
|
||||
}
|
||||
}}.resume()
|
||||
}}?.resume()
|
||||
}
|
||||
|
||||
// We had packets waiting for send when we upgraded
|
||||
@ -391,12 +391,12 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
||||
}
|
||||
|
||||
private func handleOpen(openData:String) {
|
||||
var err:NSError?
|
||||
let mesData = openData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
|
||||
|
||||
if let json = NSJSONSerialization.JSONObjectWithData(mesData,
|
||||
options: NSJSONReadingOptions.AllowFragments,
|
||||
error: &err) as? NSDictionary, sid = json["sid"] as? String {
|
||||
do {
|
||||
let json = try NSJSONSerialization.JSONObjectWithData(mesData,
|
||||
options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
|
||||
if let sid = json?["sid"] as? String {
|
||||
self.sid = sid
|
||||
_connected = true
|
||||
|
||||
@ -404,13 +404,13 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
||||
createWebsocket(andConnect: true)
|
||||
}
|
||||
|
||||
if let pingInterval = json["pingInterval"] as? Int, pingTimeout = json["pingTimeout"] as? Int {
|
||||
if let pingInterval = json?["pingInterval"] as? Int, pingTimeout = json?["pingTimeout"] as? Int {
|
||||
self.pingInterval = pingInterval / 1000
|
||||
self.pingTimeout = pingTimeout / 1000
|
||||
}
|
||||
} else {
|
||||
client?.didError("Engine failed to handshake")
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
SocketLogger.err("Error parsing open packet", client: self)
|
||||
}
|
||||
|
||||
startPingTimer()
|
||||
@ -482,19 +482,19 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
||||
|
||||
// Translatation of engine.io-parser#decodePayload
|
||||
private func parsePollingMessage(str:String) {
|
||||
if count(str) == 1 {
|
||||
if str.characters.count == 1 {
|
||||
return
|
||||
}
|
||||
|
||||
// println(str)
|
||||
|
||||
let strArray = Array(str)
|
||||
let strArray = Array(str.characters)
|
||||
var length = ""
|
||||
var n = 0
|
||||
var msg = ""
|
||||
|
||||
func testLength(length:String, inout n:Int) -> Bool {
|
||||
if let num = length.toInt() {
|
||||
if let num = Int(length) {
|
||||
n = num
|
||||
return false
|
||||
} else {
|
||||
@ -502,13 +502,13 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
||||
}
|
||||
}
|
||||
|
||||
for var i = 0, l = count(str); i < l; i++ {
|
||||
for var i = 0, l = str.characters.count; i < l; i++ {
|
||||
let chr = String(strArray[i])
|
||||
|
||||
if chr != ":" {
|
||||
length += chr
|
||||
} else {
|
||||
if length == "" || testLength(length, &n) {
|
||||
if length == "" || testLength(length, n: &n) {
|
||||
SocketLogger.err("Parsing error: %@", client: self, args: str)
|
||||
handlePollingFailed("Error parsing XHR message")
|
||||
return
|
||||
@ -516,12 +516,12 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
||||
|
||||
msg = String(strArray[i+1...i+n])
|
||||
|
||||
if let lengthInt = length.toInt() where lengthInt != count(msg) {
|
||||
if let lengthInt = Int(length) where lengthInt != msg.characters.count {
|
||||
SocketLogger.err("Parsing error: %@", client: self, args: str)
|
||||
return
|
||||
}
|
||||
|
||||
if count(msg) != 0 {
|
||||
if msg.characters.count != 0 {
|
||||
// Be sure to capture the value of the msg
|
||||
dispatch_async(handleQueue) {[weak self, msg] in
|
||||
self?.parseEngineMessage(msg, fromPolling: true)
|
||||
@ -552,7 +552,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
||||
let type = PacketType(str: (message["^(\\d)"].groups()?[1])) ?? {
|
||||
self.checkIfMessageIsBase64Binary(message)
|
||||
return PacketType.NOOP
|
||||
}()
|
||||
}()
|
||||
|
||||
switch type {
|
||||
case PacketType.MESSAGE:
|
||||
@ -612,7 +612,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
||||
|
||||
if datas != nil {
|
||||
for data in datas! {
|
||||
let (nilData, b64Data) = createBinaryDataForSend(data)
|
||||
let (_, b64Data) = createBinaryDataForSend(data)
|
||||
|
||||
postWait.append(b64Data!)
|
||||
}
|
||||
@ -633,7 +633,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
||||
|
||||
if datas != nil {
|
||||
for data in datas! {
|
||||
let (data, nilString) = createBinaryDataForSend(data)
|
||||
let (data, _) = createBinaryDataForSend(data)
|
||||
if data != nil {
|
||||
ws?.writeData(data!)
|
||||
}
|
||||
|
||||
@ -24,24 +24,24 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
private func emitAckCallback(socket:SocketIOClient, num:Int)
|
||||
(items:AnyObject...) -> Void {
|
||||
socket.emitAck(num, withData: items)
|
||||
private func emitAckCallback(socket:SocketIOClient?, num:Int?)
|
||||
(items:[AnyObject]) -> Void {
|
||||
socket?.emitAck(num ?? -1, withData: items)
|
||||
}
|
||||
|
||||
final class SocketEventHandler {
|
||||
let event:String!
|
||||
let callback:NormalCallback?
|
||||
let callback:NormalCallback
|
||||
|
||||
init(event:String, callback:NormalCallback) {
|
||||
self.event = event
|
||||
self.callback = callback
|
||||
}
|
||||
|
||||
func executeCallback(_ items:NSArray? = nil, withAck ack:Int? = nil, withAckType type:Int? = nil,
|
||||
func executeCallback(items:NSArray? = nil, withAck ack:Int? = nil, withAckType type:Int? = nil,
|
||||
withSocket socket:SocketIOClient? = nil) {
|
||||
dispatch_async(dispatch_get_main_queue()) {[weak self] in
|
||||
self?.callback?(items, ack != nil ? emitAckCallback(socket!, ack!) : nil)
|
||||
self?.callback(items, emitAckCallback(socket, num: ack))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -145,7 +145,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
|
||||
Will turn off automatic reconnects.
|
||||
Pass true to fast if you're closing from a background task
|
||||
*/
|
||||
public func close(#fast:Bool) {
|
||||
public func close(fast fast:Bool) {
|
||||
SocketLogger.log("Closing socket", client: self)
|
||||
|
||||
reconnects = false
|
||||
@ -166,7 +166,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
|
||||
/**
|
||||
Connect to the server. If we aren't connected after timeoutAfter, call handler
|
||||
*/
|
||||
public func connect(#timeoutAfter:Int, withTimeoutHandler handler:(() -> Void)?) {
|
||||
public func connect(timeoutAfter timeoutAfter:Int, withTimeoutHandler handler:(() -> Void)?) {
|
||||
if closed {
|
||||
SocketLogger.log("Warning! This socket was previously closed. This might be dangerous!", client: self)
|
||||
_closed = false
|
||||
@ -175,7 +175,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
|
||||
}
|
||||
|
||||
addEngine()
|
||||
engine?.open(opts: connectParams)
|
||||
engine?.open(connectParams)
|
||||
|
||||
if timeoutAfter == 0 {
|
||||
return
|
||||
@ -260,7 +260,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
|
||||
/**
|
||||
Same as close
|
||||
*/
|
||||
public func disconnect(#fast:Bool) {
|
||||
public func disconnect(fast fast:Bool) {
|
||||
close(fast: fast)
|
||||
}
|
||||
|
||||
@ -433,7 +433,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
|
||||
public func off(event:String) {
|
||||
SocketLogger.log("Removing handler for event: %@", client: self, args: event)
|
||||
|
||||
handlers = handlers.filter {$0.event == event ? false : true}
|
||||
handlers = ContiguousArray(handlers.filter {$0.event == event ? false : true})
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@ -24,8 +24,6 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
private let MESSAGE_LENGTH_MAX = 10000
|
||||
|
||||
protocol SocketLogClient {
|
||||
var log:Bool {get set}
|
||||
var logType:String {get}
|
||||
@ -34,16 +32,8 @@ protocol SocketLogClient {
|
||||
final class SocketLogger {
|
||||
private static let printQueue = dispatch_queue_create("printQueue", DISPATCH_QUEUE_SERIAL)
|
||||
|
||||
private static func shorten(item:AnyObject) -> CVarArgType {
|
||||
var str = toString(item)
|
||||
|
||||
if count(str) > MESSAGE_LENGTH_MAX {
|
||||
let endIndex = advance(str.startIndex, MESSAGE_LENGTH_MAX)
|
||||
|
||||
str = str.substringToIndex(endIndex)
|
||||
}
|
||||
|
||||
return str
|
||||
private static func toCVArgType(item:AnyObject) -> CVarArgType {
|
||||
return String(item)
|
||||
}
|
||||
|
||||
static func log(message:String, client:SocketLogClient, altType:String? = nil, args:AnyObject...) {
|
||||
@ -52,7 +42,7 @@ final class SocketLogger {
|
||||
}
|
||||
|
||||
dispatch_async(printQueue) {[type = client.logType] in
|
||||
let newArgs = args.map(SocketLogger.shorten)
|
||||
let newArgs = args.map(SocketLogger.toCVArgType)
|
||||
let replaced = String(format: message, arguments: newArgs)
|
||||
|
||||
NSLog("%@: %@", altType ?? type, replaced)
|
||||
@ -65,7 +55,7 @@ final class SocketLogger {
|
||||
}
|
||||
|
||||
dispatch_async(printQueue) {[type = client.logType] in
|
||||
let newArgs = args.map(SocketLogger.shorten)
|
||||
let newArgs = args.map(SocketLogger.toCVArgType)
|
||||
let replaced = String(format: message, arguments: newArgs)
|
||||
|
||||
NSLog("ERROR %@: %@", altType ?? type, replaced)
|
||||
|
||||
@ -24,7 +24,7 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
final class SocketPacket: Printable {
|
||||
final class SocketPacket: CustomStringConvertible {
|
||||
var binary = ContiguousArray<NSData>()
|
||||
var currentPlace = 0
|
||||
var data:[AnyObject]?
|
||||
@ -55,7 +55,7 @@ final class SocketPacket: Printable {
|
||||
case BINARY_ACK = 6
|
||||
|
||||
init?(str:String) {
|
||||
if let int = str.toInt(), raw = PacketType(rawValue: int) {
|
||||
if let int = Int(str), raw = PacketType(rawValue: int) {
|
||||
self = raw
|
||||
} else {
|
||||
return nil
|
||||
@ -167,8 +167,14 @@ final class SocketPacket: Printable {
|
||||
|
||||
for arg in data! {
|
||||
if arg is NSDictionary || arg is [AnyObject] {
|
||||
let jsonSend = NSJSONSerialization.dataWithJSONObject(arg,
|
||||
options: NSJSONWritingOptions(0), error: &err)
|
||||
let jsonSend: NSData?
|
||||
do {
|
||||
jsonSend = try NSJSONSerialization.dataWithJSONObject(arg,
|
||||
options: NSJSONWritingOptions(rawValue: 0))
|
||||
} catch var error as NSError {
|
||||
err = error
|
||||
jsonSend = nil
|
||||
}
|
||||
let jsonString = NSString(data: jsonSend!, encoding: NSUTF8StringEncoding)
|
||||
|
||||
message += jsonString! as String + ","
|
||||
@ -192,11 +198,11 @@ final class SocketPacket: Printable {
|
||||
}
|
||||
|
||||
func fillInPlaceholders() {
|
||||
var newArr = NSMutableArray(array: data!)
|
||||
let newArr = NSMutableArray(array: data!)
|
||||
|
||||
for i in 0..<data!.count {
|
||||
if let str = data?[i] as? String, num = str["~~(\\d)"].groups() {
|
||||
newArr[i] = binary[num[1].toInt()!]
|
||||
newArr[i] = binary[Int(num[1])!]
|
||||
} else if data?[i] is NSDictionary || data?[i] is NSArray {
|
||||
newArr[i] = _fillInPlaceholders(data![i])
|
||||
}
|
||||
@ -208,12 +214,12 @@ final class SocketPacket: Printable {
|
||||
private func _fillInPlaceholders(data:AnyObject) -> AnyObject {
|
||||
if let str = data as? String {
|
||||
if let num = str["~~(\\d)"].groups() {
|
||||
return binary[num[1].toInt()!]
|
||||
return binary[Int(num[1])!]
|
||||
} else {
|
||||
return str
|
||||
}
|
||||
} else if let dict = data as? NSDictionary {
|
||||
var newDict = NSMutableDictionary(dictionary: dict)
|
||||
let newDict = NSMutableDictionary(dictionary: dict)
|
||||
|
||||
for (key, value) in dict {
|
||||
newDict[key as! NSCopying] = _fillInPlaceholders(value)
|
||||
@ -221,7 +227,7 @@ final class SocketPacket: Printable {
|
||||
|
||||
return newDict
|
||||
} else if let arr = data as? NSArray {
|
||||
var newArr = NSMutableArray(array: arr)
|
||||
let newArr = NSMutableArray(array: arr)
|
||||
|
||||
for i in 0..<arr.count {
|
||||
newArr[i] = _fillInPlaceholders(arr[i])
|
||||
|
||||
@ -37,7 +37,7 @@ class SocketParser {
|
||||
|
||||
return placeholder
|
||||
} else if let arr = data as? NSArray {
|
||||
var newArr = NSMutableArray(array: arr)
|
||||
let newArr = NSMutableArray(array: arr)
|
||||
|
||||
for i in 0..<arr.count {
|
||||
newArr[i] = shred(arr[i])
|
||||
@ -45,7 +45,7 @@ class SocketParser {
|
||||
|
||||
return newArr
|
||||
} else if let dict = data as? NSDictionary {
|
||||
var newDict = NSMutableDictionary(dictionary: dict)
|
||||
let newDict = NSMutableDictionary(dictionary: dict)
|
||||
|
||||
for (key, value) in newDict {
|
||||
newDict[key as! NSCopying] = shred(value)
|
||||
@ -81,7 +81,7 @@ class SocketParser {
|
||||
|
||||
// Translation of socket.io-client#decodeString
|
||||
static func parseString(str:String) -> SocketPacket? {
|
||||
let arr = Array(str)
|
||||
let arr = Array(str.characters)
|
||||
let type = String(arr[0])
|
||||
|
||||
if arr.count == 1 {
|
||||
@ -103,7 +103,7 @@ class SocketParser {
|
||||
}
|
||||
}
|
||||
|
||||
if let holders = buf.toInt() where arr[i] == "-" {
|
||||
if let holders = Int(buf) where arr[i] == "-" {
|
||||
placeholders = holders
|
||||
} else {
|
||||
NSLog("Error parsing \(str)")
|
||||
@ -130,10 +130,10 @@ class SocketParser {
|
||||
|
||||
let next = String(arr[i + 1])
|
||||
|
||||
if next.toInt() != nil {
|
||||
if Int(next) != nil {
|
||||
var c = ""
|
||||
while ++i < arr.count {
|
||||
if let int = String(arr[i]).toInt() {
|
||||
if let int = Int(String(arr[i])) {
|
||||
c += String(arr[i])
|
||||
} else {
|
||||
--i
|
||||
@ -141,11 +141,11 @@ class SocketParser {
|
||||
}
|
||||
}
|
||||
|
||||
id = c.toInt()
|
||||
id = Int(c)
|
||||
}
|
||||
|
||||
if ++i < arr.count {
|
||||
let d = str[advance(str.startIndex, i)...advance(str.startIndex, count(str)-1)]
|
||||
let d = str[advance(str.startIndex, i)...advance(str.startIndex, str.characters.count-1)]
|
||||
let noPlaceholders = d["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"] ~= "\"~~$2\""
|
||||
let data = SocketParser.parseData(noPlaceholders) as? [AnyObject] ?? [noPlaceholders]
|
||||
|
||||
@ -160,8 +160,14 @@ class SocketParser {
|
||||
static func parseData(data:String) -> AnyObject? {
|
||||
var err:NSError?
|
||||
let stringData = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
|
||||
let parsed:AnyObject? = NSJSONSerialization.JSONObjectWithData(stringData!,
|
||||
options: NSJSONReadingOptions.MutableContainers, error: &err)
|
||||
let parsed:AnyObject?
|
||||
do {
|
||||
parsed = try NSJSONSerialization.JSONObjectWithData(stringData!,
|
||||
options: NSJSONReadingOptions.MutableContainers)
|
||||
} catch var error as NSError {
|
||||
err = error
|
||||
parsed = nil
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
// println(err)
|
||||
|
||||
@ -28,7 +28,7 @@ import Foundation
|
||||
// Objective-C blocks are copied, but Objective-C assumes that Swift will copy it.
|
||||
// And the way things are done here, the bridging fails to copy the block in
|
||||
// SocketAckMap#addAck
|
||||
public typealias AckCallback = @objc_block (NSArray?) -> Void
|
||||
public typealias AckEmitter = (AnyObject...) -> Void
|
||||
public typealias AckCallback = @convention(block) (NSArray?) -> Void
|
||||
public typealias AckEmitter = ([AnyObject]) -> Void
|
||||
public typealias NormalCallback = (NSArray?, AckEmitter?) -> Void
|
||||
public typealias OnAckCallback = (timeout:UInt64, callback:AckCallback) -> Void
|
||||
|
||||
@ -18,34 +18,36 @@ var swiftRegexCache = [String: NSRegularExpression]()
|
||||
public class SwiftRegex: NSObject, BooleanType {
|
||||
var target:String
|
||||
var regex: NSRegularExpression
|
||||
|
||||
init(target:String, pattern:String, options:NSRegularExpressionOptions = nil) {
|
||||
|
||||
init(target:String, pattern:String, options:NSRegularExpressionOptions?) {
|
||||
self.target = target
|
||||
if let regex = swiftRegexCache[pattern] {
|
||||
self.regex = regex
|
||||
} else {
|
||||
var error: NSError?
|
||||
if let regex = NSRegularExpression(pattern: pattern, options:options, error:&error) {
|
||||
do {
|
||||
let regex = try NSRegularExpression(pattern: pattern, options:
|
||||
NSRegularExpressionOptions.DotMatchesLineSeparators)
|
||||
swiftRegexCache[pattern] = regex
|
||||
self.regex = regex
|
||||
}
|
||||
else {
|
||||
} catch let error1 as NSError {
|
||||
error = error1
|
||||
SwiftRegex.failure("Error in pattern: \(pattern) - \(error)")
|
||||
self.regex = NSRegularExpression()
|
||||
}
|
||||
}
|
||||
super.init()
|
||||
}
|
||||
|
||||
|
||||
class func failure(message: String) {
|
||||
println("SwiftRegex: "+message)
|
||||
print("SwiftRegex: "+message)
|
||||
//assert(false,"SwiftRegex: failed")
|
||||
}
|
||||
|
||||
|
||||
final var targetRange: NSRange {
|
||||
return NSRange(location: 0,length: count(target.utf16))
|
||||
return NSRange(location: 0,length: target.utf16.count)
|
||||
}
|
||||
|
||||
|
||||
final func substring(range: NSRange) -> String? {
|
||||
if ( range.location != NSNotFound ) {
|
||||
return (target as NSString).substringWithRange(range)
|
||||
@ -53,23 +55,24 @@ public class SwiftRegex: NSObject, BooleanType {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
public func doesMatch(options: NSMatchingOptions = nil) -> Bool {
|
||||
return range(options: options).location != NSNotFound
|
||||
|
||||
public func doesMatch(options: NSMatchingOptions!) -> Bool {
|
||||
return range(options).location != NSNotFound
|
||||
}
|
||||
|
||||
public func range(options: NSMatchingOptions = nil) -> NSRange {
|
||||
return regex.rangeOfFirstMatchInString(target as String, options: nil, range: targetRange)
|
||||
|
||||
public func range(options: NSMatchingOptions) -> NSRange {
|
||||
return regex.rangeOfFirstMatchInString(target as String, options: [], range: targetRange)
|
||||
}
|
||||
|
||||
public func match(options: NSMatchingOptions = nil) -> String? {
|
||||
return substring(range(options: options))
|
||||
|
||||
public func match(options: NSMatchingOptions) -> String? {
|
||||
return substring(range(options))
|
||||
}
|
||||
|
||||
public func groups(options: NSMatchingOptions = nil) -> [String]? {
|
||||
return groupsForMatch(regex.firstMatchInString(target as String, options: options, range: targetRange))
|
||||
|
||||
public func groups() -> [String]? {
|
||||
return groupsForMatch(regex.firstMatchInString(target as String, options:
|
||||
NSMatchingOptions.WithoutAnchoringBounds, range: targetRange))
|
||||
}
|
||||
|
||||
|
||||
func groupsForMatch(match: NSTextCheckingResult!) -> [String]? {
|
||||
if match != nil {
|
||||
var groups = [String]()
|
||||
@ -85,80 +88,75 @@ public class SwiftRegex: NSObject, BooleanType {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public subscript(groupno: Int) -> String? {
|
||||
get {
|
||||
return groups()?[groupno]
|
||||
}
|
||||
|
||||
|
||||
set(newValue) {
|
||||
if newValue == nil {
|
||||
return
|
||||
}
|
||||
|
||||
for match in matchResults()!.reverse() {
|
||||
|
||||
for match in Array(matchResults().reverse()) {
|
||||
let replacement = regex.replacementStringForResult(match,
|
||||
inString: target as String, offset: 0, template: newValue!)
|
||||
let mut = NSMutableString(string: target)
|
||||
mut.replaceCharactersInRange(match.rangeAtIndex(groupno), withString: replacement)
|
||||
|
||||
|
||||
target = mut as String
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func matchResults(options: NSMatchingOptions = nil) -> [NSTextCheckingResult]? {
|
||||
let matches = regex.matchesInString(target as String, options: options, range: targetRange)
|
||||
as? [NSTextCheckingResult]
|
||||
|
||||
if matches != nil {
|
||||
return matches!
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
|
||||
func matchResults() -> [NSTextCheckingResult] {
|
||||
let matches = regex.matchesInString(target as String, options:
|
||||
NSMatchingOptions.WithoutAnchoringBounds, range: targetRange)
|
||||
as [NSTextCheckingResult]
|
||||
|
||||
return matches
|
||||
}
|
||||
|
||||
public func ranges(options: NSMatchingOptions = nil) -> [NSRange] {
|
||||
return matchResults(options: options)!.map { $0.range }
|
||||
|
||||
public func ranges() -> [NSRange] {
|
||||
return matchResults().map { $0.range }
|
||||
}
|
||||
|
||||
public func matches(options: NSMatchingOptions = nil) -> [String] {
|
||||
return matchResults(options: options)!.map( { self.substring($0.range)!})
|
||||
|
||||
public func matches() -> [String] {
|
||||
return matchResults().map( { self.substring($0.range)!})
|
||||
}
|
||||
|
||||
public func allGroups(options: NSMatchingOptions = nil) -> [[String]?] {
|
||||
return matchResults(options: options)!.map {self.groupsForMatch($0)}
|
||||
|
||||
public func allGroups() -> [[String]?] {
|
||||
return matchResults().map {self.groupsForMatch($0)}
|
||||
}
|
||||
|
||||
public func dictionary(options: NSMatchingOptions = nil) -> Dictionary<String,String> {
|
||||
|
||||
public func dictionary(options: NSMatchingOptions!) -> Dictionary<String,String> {
|
||||
var out = Dictionary<String,String>()
|
||||
for match in matchResults(options: options)! {
|
||||
for match in matchResults() {
|
||||
out[substring(match.rangeAtIndex(1))!] = substring(match.rangeAtIndex(2))!
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
|
||||
func substituteMatches(substitution: ((NSTextCheckingResult, UnsafeMutablePointer<ObjCBool>) -> String),
|
||||
options:NSMatchingOptions = nil) -> String {
|
||||
options:NSMatchingOptions) -> String {
|
||||
let out = NSMutableString()
|
||||
var pos = 0
|
||||
|
||||
regex.enumerateMatchesInString(target as String, options: options, range: targetRange ) {
|
||||
(match: NSTextCheckingResult!, flags: NSMatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) in
|
||||
|
||||
let matchRange = match.range
|
||||
|
||||
regex.enumerateMatchesInString(target as String, options: options, range: targetRange ) {match, flags, stop in
|
||||
let matchRange = match!.range
|
||||
out.appendString( self.substring(NSRange(location:pos, length:matchRange.location-pos))!)
|
||||
out.appendString( substitution(match, stop) )
|
||||
out.appendString( substitution(match!, stop) )
|
||||
pos = matchRange.location + matchRange.length
|
||||
}
|
||||
|
||||
|
||||
out.appendString(substring(NSRange(location:pos, length:targetRange.length-pos))!)
|
||||
|
||||
|
||||
return out as String
|
||||
}
|
||||
|
||||
|
||||
public var boolValue: Bool {
|
||||
return doesMatch()
|
||||
return doesMatch(nil)
|
||||
}
|
||||
}
|
||||
|
||||
@ -170,7 +168,7 @@ extension String {
|
||||
|
||||
extension String {
|
||||
public subscript(pattern: String) -> SwiftRegex {
|
||||
return SwiftRegex(target: self, pattern: pattern)
|
||||
return SwiftRegex(target: self, pattern: pattern, options: nil)
|
||||
}
|
||||
}
|
||||
|
||||
@ -178,20 +176,20 @@ public func ~= (left: SwiftRegex, right: String) -> String {
|
||||
return left.substituteMatches({match, stop in
|
||||
return left.regex.replacementStringForResult( match,
|
||||
inString: left.target as String, offset: 0, template: right )
|
||||
}, options: nil)
|
||||
}, options: [])
|
||||
}
|
||||
|
||||
public func ~= (left: SwiftRegex, right: [String]) -> String {
|
||||
var matchNumber = 0
|
||||
return left.substituteMatches({match, stop -> String in
|
||||
|
||||
|
||||
if ++matchNumber == right.count {
|
||||
stop.memory = true
|
||||
}
|
||||
|
||||
|
||||
return left.regex.replacementStringForResult( match,
|
||||
inString: left.target as String, offset: 0, template: right[matchNumber-1] )
|
||||
}, options: nil)
|
||||
}, options: [])
|
||||
}
|
||||
|
||||
public func ~= (left: SwiftRegex, right: (String) -> String) -> String {
|
||||
@ -199,11 +197,11 @@ public func ~= (left: SwiftRegex, right: (String) -> String) -> String {
|
||||
return left.substituteMatches(
|
||||
{match, stop -> String in
|
||||
right(left.substring(match.range)!)
|
||||
}, options: nil)
|
||||
}, options: [])
|
||||
}
|
||||
|
||||
public func ~= (left: SwiftRegex, right: ([String]?) -> String) -> String {
|
||||
return left.substituteMatches({match, stop -> String in
|
||||
return right(left.groupsForMatch(match))
|
||||
}, options: nil)
|
||||
}, options: [])
|
||||
}
|
||||
|
||||
@ -169,7 +169,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
//private method that starts the connection
|
||||
private func createHTTPRequest() {
|
||||
|
||||
let str: NSString = url.absoluteString!
|
||||
let str: NSString = url.absoluteString
|
||||
let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET",
|
||||
url, kCFHTTPVersion1_1)
|
||||
|
||||
@ -185,7 +185,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
if self.cookies != nil {
|
||||
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(self.cookies!)
|
||||
for (key, value) in headers {
|
||||
self.addHeader(urlRequest, key: key as! String, val: value as! String)
|
||||
self.addHeader(urlRequest, key: key as String, val: value as String)
|
||||
}
|
||||
}
|
||||
|
||||
@ -196,14 +196,14 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
self.addHeader(urlRequest, key: headerWSVersionName, val: headerWSVersionValue)
|
||||
self.addHeader(urlRequest, key: headerWSKeyName, val: self.generateWebSocketKey())
|
||||
self.addHeader(urlRequest, key: headerOriginName, val: url.absoluteString!)
|
||||
self.addHeader(urlRequest, key: headerOriginName, val: url.absoluteString)
|
||||
self.addHeader(urlRequest, key: headerWSHostName, val: "\(url.host!):\(port!)")
|
||||
for (key,value) in headers {
|
||||
self.addHeader(urlRequest, key: key, val: value)
|
||||
}
|
||||
|
||||
let serializedRequest: NSData = CFHTTPMessageCopySerializedMessage(urlRequest.takeUnretainedValue()).takeUnretainedValue()
|
||||
self.initStreamsWithData(serializedRequest, Int(port!))
|
||||
let serializedRequest = CFHTTPMessageCopySerializedMessage(urlRequest.takeUnretainedValue())?.takeUnretainedValue()
|
||||
self.initStreamsWithData(serializedRequest!, Int(port!))
|
||||
}
|
||||
//Add a header to the CFHTTPMessage by using the NSString bridges to CFString
|
||||
private func addHeader(urlRequest: Unmanaged<CFHTTPMessage>,key: String, val: String) {
|
||||
@ -221,8 +221,8 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25)))
|
||||
key += "\(Character(uni))"
|
||||
}
|
||||
var data = key.dataUsingEncoding(NSUTF8StringEncoding)
|
||||
var baseKey = data?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(0))
|
||||
let data = key.dataUsingEncoding(NSUTF8StringEncoding)
|
||||
let baseKey = data?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
|
||||
return baseKey!
|
||||
}
|
||||
//Start the stream connection and write the data to the output stream
|
||||
@ -260,7 +260,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
let bytes = UnsafePointer<UInt8>(data.bytes)
|
||||
outputStream!.write(bytes, maxLength: data.length)
|
||||
while(isRunLoop) {
|
||||
NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate.distantFuture() as! NSDate)
|
||||
NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate.distantFuture() as NSDate)
|
||||
}
|
||||
}
|
||||
//delegate for the stream methods. Processes incoming bytes
|
||||
@ -300,7 +300,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
///handles the incoming bytes and sending them to the proper processing method
|
||||
private func processInputStream() {
|
||||
let buf = NSMutableData(capacity: BUFFER_MAX)
|
||||
var buffer = UnsafeMutablePointer<UInt8>(buf!.bytes)
|
||||
let buffer = UnsafeMutablePointer<UInt8>(buf!.bytes)
|
||||
let length = inputStream!.read(buffer, maxLength: BUFFER_MAX)
|
||||
if length > 0 {
|
||||
if !connected {
|
||||
@ -333,7 +333,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
let data = inputQueue[0]
|
||||
var work = data
|
||||
if (fragBuffer != nil) {
|
||||
var combine = NSMutableData(data: fragBuffer!)
|
||||
let combine = NSMutableData(data: fragBuffer!)
|
||||
combine.appendData(data)
|
||||
work = combine
|
||||
fragBuffer = nil
|
||||
@ -388,8 +388,8 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
return false
|
||||
}
|
||||
let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response)
|
||||
let headers: NSDictionary = cfHeaders.takeRetainedValue()
|
||||
let acceptKey = headers[headerWSAcceptName] as! NSString
|
||||
let headers:NSDictionary? = cfHeaders?.takeRetainedValue()
|
||||
let acceptKey = headers?[headerWSAcceptName] as! NSString
|
||||
if acceptKey.length > 0 {
|
||||
return true
|
||||
}
|
||||
@ -398,7 +398,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
|
||||
///process the websocket data
|
||||
private func processRawMessage(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
|
||||
var response = readStack.last
|
||||
let response = readStack.last
|
||||
if response != nil && bufferLen < 2 {
|
||||
fragBuffer = NSData(bytes: buffer, length: bufferLen)
|
||||
return
|
||||
@ -414,7 +414,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
resp.bytesLeft -= len
|
||||
resp.buffer?.appendData(NSData(bytes: buffer, length: len))
|
||||
processResponse(resp)
|
||||
var offset = bufferLen - extra
|
||||
let offset = bufferLen - extra
|
||||
if extra > 0 {
|
||||
processExtra((buffer+offset), bufferLen: extra)
|
||||
}
|
||||
@ -473,7 +473,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
let len = Int(payloadLen-2)
|
||||
if len > 0 {
|
||||
let bytes = UnsafePointer<UInt8>((buffer+offset))
|
||||
var str: NSString? = NSString(data: NSData(bytes: bytes, length: len), encoding: NSUTF8StringEncoding)
|
||||
let str: NSString? = NSString(data: NSData(bytes: bytes, length: len), encoding: NSUTF8StringEncoding)
|
||||
if str == nil {
|
||||
code = CloseCode.ProtocolError.rawValue
|
||||
}
|
||||
@ -603,7 +603,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
let data = response.buffer! //local copy so it is perverse for writing
|
||||
dequeueWrite(data, code: OpCode.Pong)
|
||||
} else if response.code == .TextFrame {
|
||||
var str: NSString? = NSString(data: response.buffer!, encoding: NSUTF8StringEncoding)
|
||||
let str: NSString? = NSString(data: response.buffer!, encoding: NSUTF8StringEncoding)
|
||||
if str == nil {
|
||||
writeError(CloseCode.Encoding.rawValue)
|
||||
return false
|
||||
@ -640,7 +640,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
///write a an error to the socket
|
||||
private func writeError(code: UInt16) {
|
||||
let buf = NSMutableData(capacity: sizeof(UInt16))
|
||||
var buffer = UnsafeMutablePointer<UInt16>(buf!.bytes)
|
||||
let buffer = UnsafeMutablePointer<UInt16>(buf!.bytes)
|
||||
buffer[0] = code.byteSwapped
|
||||
dequeueWrite(NSData(bytes: buffer, length: sizeof(UInt16)), code: .ConnectionClose)
|
||||
}
|
||||
@ -675,12 +675,12 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
buffer[1] = CUnsignedChar(dataLength)
|
||||
} else if dataLength <= Int(UInt16.max) {
|
||||
buffer[1] = 126
|
||||
var sizeBuffer = UnsafeMutablePointer<UInt16>((buffer+offset))
|
||||
let sizeBuffer = UnsafeMutablePointer<UInt16>((buffer+offset))
|
||||
sizeBuffer[0] = UInt16(dataLength).byteSwapped
|
||||
offset += sizeof(UInt16)
|
||||
} else {
|
||||
buffer[1] = 127
|
||||
var sizeBuffer = UnsafeMutablePointer<UInt64>((buffer+offset))
|
||||
let sizeBuffer = UnsafeMutablePointer<UInt64>((buffer+offset))
|
||||
sizeBuffer[0] = UInt64(dataLength).byteSwapped
|
||||
offset += sizeof(UInt64)
|
||||
}
|
||||
@ -699,7 +699,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
break
|
||||
}
|
||||
let writeBuffer = UnsafePointer<UInt8>(frame!.bytes+total)
|
||||
var len = self.outputStream?.write(writeBuffer, maxLength: offset-total)
|
||||
let len = self.outputStream?.write(writeBuffer, maxLength: offset-total)
|
||||
if len == nil || len! < 0 {
|
||||
var error: NSError?
|
||||
if let streamError = self.outputStream?.streamError {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user