1
0
Эх сурвалжийг харах

Add the trailing whitespace rule in Swiftlint

* Autocorrect the new rule in Swiftlint to remove all the trailing whitespaces
* Update the CHANGELOG
Victor Sigler 7 жил өмнө
parent
commit
8db2708fe7

+ 0 - 1
.swiftlint.yml

@@ -13,7 +13,6 @@ identifier_name:
 disabled_rules:
   - line_length
   - statement_position
-  - trailing_whitespace
 
 excluded: # paths to ignore during linting. Takes precedence over `included`.
   - LinuxMain.swift

+ 3 - 1
CHANGELOG.md

@@ -18,7 +18,9 @@ All notable changes to this project will be documented in this file. Changes not
 
 # [Unreleased]
 
-* Nothing yet.
+## Added
+
+- Add the `trailing_whitespace` rule in Swiftlint and autocorrect all the source files. ([#416](https://github.com/httpswift/swifter/pull/416)) by [@Vkt0r](https://github.com/Vkt0r)
 
 # [1.4.7] 
 

+ 30 - 31
XCode/Sources/DemoServer.swift

@@ -9,11 +9,11 @@ import Foundation
 
 // swiftlint:disable function_body_length
 public func demoServer(_ publicDir: String) -> HttpServer {
-    
+
     print(publicDir)
-    
+
     let server = HttpServer()
-    
+
     server["/public/:path"] = shareFilesFromDirectory(publicDir)
 
     server["/files/:path"] = directoryBrowser("/")
@@ -29,9 +29,9 @@ public func demoServer(_ publicDir: String) -> HttpServer {
             }
         }
     }
-    
+
     server["/magic"] = { .ok(.htmlBody("You asked for " + $0.path)) }
-    
+
     server["/test/:param1/:param2"] = { request in
         scopes {
             html {
@@ -39,27 +39,27 @@ public func demoServer(_ publicDir: String) -> HttpServer {
                     h3 { inner = "Address: \(request.address ?? "unknown")" }
                     h3 { inner = "Url: \(request.path)" }
                     h3 { inner = "Method: \(request.method)" }
-                    
+
                     h3 { inner = "Query:" }
-                    
+
                     table(request.queryParams) { param in
                         tr {
                             td { inner = param.0 }
                             td { inner = param.1 }
                         }
                     }
-                    
+
                     h3 { inner = "Headers:" }
-                    
+
                     table(request.headers) { header in
                         tr {
                             td { inner = header.0 }
                             td { inner = header.1 }
                         }
                     }
-                    
+
                     h3 { inner = "Route params:" }
-                    
+
                     table(request.params) { param in
                         tr {
                             td { inner = param.0 }
@@ -70,7 +70,7 @@ public func demoServer(_ publicDir: String) -> HttpServer {
             }
         }(request)
     }
-    
+
     server.GET["/upload"] = scopes {
         html {
             body {
@@ -78,11 +78,11 @@ public func demoServer(_ publicDir: String) -> HttpServer {
                     method = "POST"
                     action = "/upload"
                     enctype = "multipart/form-data"
-                    
+
                     input { name = "my_file1"; type = "file" }
                     input { name = "my_file2"; type = "file" }
                     input { name = "my_file3"; type = "file" }
-                    
+
                     button {
                         type = "submit"
                         inner = "Upload"
@@ -91,7 +91,7 @@ public func demoServer(_ publicDir: String) -> HttpServer {
             }
         }
     }
-    
+
     server.POST["/upload"] = { request in
         var response = ""
         for multipart in request.parseMultiPartFormData() {
@@ -100,7 +100,7 @@ public func demoServer(_ publicDir: String) -> HttpServer {
         }
         return HttpResponse.ok(.htmlBody(response))
     }
-    
+
     server.GET["/login"] = scopes {
         html {
             head {
@@ -109,11 +109,11 @@ public func demoServer(_ publicDir: String) -> HttpServer {
             }
             body {
                 h3 { inner = "Sign In" }
-                
+
                 form {
                     method = "POST"
                     action = "/login"
-                    
+
                     fieldset {
                         input { placeholder = "E-mail"; name = "email"; type = "email"; autofocus = "" }
                         input { placeholder = "Password"; name = "password"; type = "password"; autofocus = "" }
@@ -125,7 +125,7 @@ public func demoServer(_ publicDir: String) -> HttpServer {
                             }
                         }
                     }
-                    
+
                 }
                 javascript {
                     src = "http://cdn.staticfile.org/twitter-bootstrap/3.3.0/js/bootstrap.min.js"
@@ -133,12 +133,12 @@ public func demoServer(_ publicDir: String) -> HttpServer {
             }
         }
     }
-    
+
     server.POST["/login"] = { request in
         let formFields = request.parseUrlencodedForm()
         return HttpResponse.ok(.htmlBody(formFields.map({ "\($0.0) = \($0.1)" }).joined(separator: "<br>")))
     }
-    
+
     server["/demo"] = scopes {
         html {
             body {
@@ -149,15 +149,15 @@ public func demoServer(_ publicDir: String) -> HttpServer {
             }
         }
     }
-    
+
     server["/raw"] = { _ in
         return HttpResponse.raw(200, "OK", ["XXX-Custom-Header": "value"], { try $0.write([UInt8]("test".utf8)) })
     }
-    
+
     server["/redirect/permanently"] = { _ in
         return .movedPermanently("http://www.google.com")
     }
-    
+
     server["/redirect/temporarily"] = { _ in
         return .movedTemporarily("http://www.google.com")
     }
@@ -167,11 +167,11 @@ public func demoServer(_ publicDir: String) -> HttpServer {
         for index in 0..<1000 { longResponse += "(\(index)),->" }
         return .ok(.htmlBody(longResponse))
     }
-    
+
     server["/wildcard/*/test/*/:param"] = { request in
         return .ok(.htmlBody(request.path))
     }
-    
+
     server["/stream"] = { _ in
         return HttpResponse.raw(200, "OK", nil, { writer in
             for index in 0...100 {
@@ -179,7 +179,7 @@ public func demoServer(_ publicDir: String) -> HttpServer {
             }
         })
     }
-    
+
     server["/websocket-echo"] = websocket(text: { (session, text) in
         session.writeText(text)
     }, binary: { (session, binary) in
@@ -191,16 +191,15 @@ public func demoServer(_ publicDir: String) -> HttpServer {
     }, disconnected: { _ in
         // Client disconnected
     })
-    
+
     server.notFoundHandler = { _ in
         return .movedPermanently("https://github.com/404")
     }
-    
+
     server.middleware.append { request in
         print("Middleware: \(request.address ?? "unknown address") -> \(request.method) -> \(request.path)")
         return nil
     }
-    
+
     return server
 }
-    

+ 1 - 1
XCode/Sources/Errno.swift

@@ -8,7 +8,7 @@
 import Foundation
 
 public class Errno {
-    
+
     public class func description() -> String {
         // https://forums.developer.apple.com/thread/113919
         return String(cString: strerror(errno))

+ 3 - 3
XCode/Sources/Files.swift

@@ -35,16 +35,16 @@ public func shareFilesFromDirectory(_ directoryPath: String, defaults: [String]
             }
         }
         let filePath = directoryPath + String.pathSeparator + fileRelativePath.value
-        
+
         if let file = try? filePath.openForReading() {
             let mimeType = fileRelativePath.value.mimeType()
             var responseHeader: [String: String] = ["Content-Type": mimeType]
-            
+
             if let attr = try? FileManager.default.attributesOfItem(atPath: filePath),
                 let fileSize = attr[FileAttributeKey.size] as? UInt64 {
                 responseHeader["Content-Length"] = String(fileSize)
             }
-            
+
             return .raw(200, "OK", responseHeader, { writer in
                 try? writer.write(file)
                 file.close()

+ 4 - 4
XCode/Sources/HttpParser.swift

@@ -12,9 +12,9 @@ enum HttpParserError: Error {
 }
 
 public class HttpParser {
-    
+
     public init() { }
-    
+
     public func readHttpRequest(_ socket: Socket) throws -> HttpRequest {
         let statusLine = try socket.readLine()
         let statusLineTokens = statusLine.components(separatedBy: " ")
@@ -36,7 +36,7 @@ public class HttpParser {
     private func readBody(_ socket: Socket, size: Int) throws -> [UInt8] {
         return try socket.read(length: size)
     }
-    
+
     private func readHeaders(_ socket: Socket) throws -> [String: String] {
         var headers = [String: String]()
         while case let headerLine = try socket.readLine(), !headerLine.isEmpty {
@@ -47,7 +47,7 @@ public class HttpParser {
         }
         return headers
     }
-    
+
     func supportsKeepAlive(_ headers: [String: String]) -> Bool {
         if let value = headers["connection"] {
             return "keep-alive" == value.trimmingCharacters(in: .whitespaces)

+ 15 - 15
XCode/Sources/HttpRequest.swift

@@ -8,7 +8,7 @@
 import Foundation
 
 public class HttpRequest {
-    
+
     public var path: String = ""
     public var queryParams: [(String, String)] = []
     public var method: String = ""
@@ -16,16 +16,16 @@ public class HttpRequest {
     public var body: [UInt8] = []
     public var address: String? = ""
     public var params: [String: String] = [:]
-    
+
     public init() {}
-    
+
     public func hasTokenForHeader(_ headerName: String, token: String) -> Bool {
         guard let headerValue = headers[headerName] else {
             return false
         }
         return headerValue.components(separatedBy: ",").filter({ $0.trimmingCharacters(in: .whitespaces).lowercased() == token }).count > 0
     }
-    
+
     public func parseUrlencodedForm() -> [(String, String)] {
         guard let contentTypeHeader = headers["content-type"] else {
             return []
@@ -47,20 +47,20 @@ public class HttpRequest {
             return ("", "")
         }
     }
-    
+
     public struct MultiPart {
-        
+
         public let headers: [String: String]
         public let body: [UInt8]
-        
+
         public var name: String? {
             return valueFor("content-disposition", parameter: "name")?.unquote()
         }
-        
+
         public var fileName: String? {
             return valueFor("content-disposition", parameter: "filename")?.unquote()
         }
-        
+
         private func valueFor(_ headerName: String, parameter: String) -> String? {
             return headers.reduce([String]()) { (combined, header: (key: String, value: String)) -> [String] in
                 guard header.key == headerName else {
@@ -77,7 +77,7 @@ public class HttpRequest {
                 }.first
         }
     }
-    
+
     public func parseMultiPartFormData() -> [MultiPart] {
         guard let contentTypeHeader = headers["content-type"] else {
             return []
@@ -98,7 +98,7 @@ public class HttpRequest {
         }
         return []
     }
-    
+
     private func parseMultiPartFormData(_ data: [UInt8], boundary: String) -> [MultiPart] {
         var generator = data.makeIterator()
         var result = [MultiPart]()
@@ -107,7 +107,7 @@ public class HttpRequest {
         }
         return result
     }
-    
+
     private func nextMultiPart(_ generator: inout IndexingIterator<[UInt8]>, boundary: String, isFirst: Bool) -> MultiPart? {
         if isFirst {
             guard nextUTF8MultiPartLine(&generator) == boundary else {
@@ -128,7 +128,7 @@ public class HttpRequest {
         }
         return MultiPart(headers: headers, body: body)
     }
-    
+
     private func nextUTF8MultiPartLine(_ generator: inout IndexingIterator<[UInt8]>) -> String? {
         var temp = [UInt8]()
         while let value = generator.next() {
@@ -141,11 +141,11 @@ public class HttpRequest {
         }
         return String(bytes: temp, encoding: String.Encoding.utf8)
     }
-    
+
     // swiftlint:disable identifier_name
     static let CR = UInt8(13)
     static let NL = UInt8(10)
-    
+
     private func nextMultiPartBody(_ generator: inout IndexingIterator<[UInt8]>, boundary: String) -> [UInt8]? {
         var body = [UInt8]()
         let boundaryArray = [UInt8](boundary.utf8)

+ 1 - 1
XCode/Sources/HttpResponse.swift

@@ -21,7 +21,7 @@ public protocol HttpResponseBodyWriter {
 }
 
 public enum HttpResponseBody {
-    
+
     case json(Any)
     case html(String)
     case htmlBody(String)

+ 31 - 31
XCode/Sources/HttpRouter.swift

@@ -8,23 +8,23 @@
 import Foundation
 
 open class HttpRouter {
-    
+
     public init() {}
-    
+
     private class Node {
-        
+
         /// The children nodes that form the route
         var nodes = [String: Node]()
-        
+
         /// Define whether or not this node is the end of a route
         var isEndOfRoute: Bool = false
-        
+
         /// The closure to handle the route
         var handler: ((HttpRequest) -> HttpResponse)?
     }
-    
+
     private var rootNode = Node()
-    
+
     /// The Queue to handle the thread safe access to the routes
     private let queue = DispatchQueue(label: "swifter.httpserverio.httprouter")
 
@@ -35,7 +35,7 @@ open class HttpRouter {
         }
         return routes
     }
-    
+
     private func routesForNode(_ node: Node, prefix: String = "") -> [String] {
         var result = [String]()
         if node.handler != nil {
@@ -46,7 +46,7 @@ open class HttpRouter {
         }
         return result
     }
-    
+
     public func register(_ method: String?, path: String, handler: ((HttpRequest) -> HttpResponse)?) {
         var pathSegments = stripQuery(path).split("/")
         if let method = method {
@@ -57,9 +57,9 @@ open class HttpRouter {
         var pathSegmentsGenerator = pathSegments.makeIterator()
         inflate(&rootNode, generator: &pathSegmentsGenerator).handler = handler
     }
-    
+
     public func route(_ method: String?, path: String) -> ([String: String], (HttpRequest) -> HttpResponse)? {
-        
+
         return queue.sync {
             if let method = method {
                 let pathSegments = (method + "/" + stripQuery(path)).split("/")
@@ -69,22 +69,22 @@ open class HttpRouter {
                     return (params, handler)
                 }
             }
-            
+
             let pathSegments = ("*/" + stripQuery(path)).split("/")
             var pathSegmentsGenerator = pathSegments.makeIterator()
             var params = [String: String]()
             if let handler = findHandler(&rootNode, params: &params, generator: &pathSegmentsGenerator) {
                 return (params, handler)
             }
-            
+
             return nil
         }
     }
-    
+
     private func inflate(_ node: inout Node, generator: inout IndexingIterator<[String]>) -> Node {
-        
+
         var currentNode = node
-        
+
         while let pathSegment = generator.next() {
             if let nextNode = currentNode.nodes[pathSegment] {
                 currentNode = nextNode
@@ -93,21 +93,21 @@ open class HttpRouter {
                 currentNode = currentNode.nodes[pathSegment]!
             }
         }
-        
+
         currentNode.isEndOfRoute = true
         return currentNode
     }
-    
+
     private func findHandler(_ node: inout Node, params: inout [String: String], generator: inout IndexingIterator<[String]>) -> ((HttpRequest) -> HttpResponse)? {
-        
+
         var matchedRoutes = [Node]()
         let pattern = generator.map { $0 }
         let numberOfElements = pattern.count
-        
+
         findHandler(&node, params: &params, pattern: pattern, matchedNodes: &matchedRoutes, index: 0, count: numberOfElements)
         return matchedRoutes.first?.handler
     }
-    
+
     // swiftlint:disable function_parameter_count
     /// Find the handlers for a specified route
     ///
@@ -119,9 +119,9 @@ open class HttpRouter {
     ///   - index: The index of current position in the generator
     ///   - count: The number of elements if the route to match
     private func findHandler(_ node: inout Node, params: inout [String: String], pattern: [String], matchedNodes: inout [Node], index: Int, count: Int) {
-    
+
         if index < count, let pathToken = pattern[index].removingPercentEncoding {
-            
+
             var currentIndex = index + 1
             let variableNodes = node.nodes.filter { $0.0.first == ":" }
             if let variableNode = variableNodes.first {
@@ -134,22 +134,22 @@ open class HttpRouter {
                     } else {
                         params[variableNode.0] = pathToken
                     }
-                    
+
                     matchedNodes.append(variableNode.value)
                     return
                 }
                 params[variableNode.0] = pathToken
                 findHandler(&node.nodes[variableNode.0]!, params: &params, pattern: pattern, matchedNodes: &matchedNodes, index: currentIndex, count: count)
             }
-            
+
             if var node = node.nodes[pathToken] {
                 findHandler(&node, params: &params, pattern: pattern, matchedNodes: &matchedNodes, index: currentIndex, count: count)
             }
-            
+
             if var node = node.nodes["*"] {
                 findHandler(&node, params: &params, pattern: pattern, matchedNodes: &matchedNodes, index: currentIndex, count: count)
             }
-            
+
             if let startStarNode = node.nodes["**"] {
                 let startStarNodeKeys = startStarNode.nodes.keys
                 currentIndex += 1
@@ -161,14 +161,14 @@ open class HttpRouter {
                 }
             }
         }
-        
+
         if node.isEndOfRoute && index == count {
             // if it's the last element and the path to match is done then it's a pattern matching
             matchedNodes.append(node)
             return
         }
     }
-    
+
     private func stripQuery(_ path: String) -> String {
         if let path = path.components(separatedBy: "?").first {
             return path
@@ -178,9 +178,9 @@ open class HttpRouter {
 }
 
 extension String {
-    
+
     func split(_ separator: Character) -> [String] {
         return self.split { $0 == separator }.map(String.init)
     }
-    
+
 }

+ 10 - 10
XCode/Sources/HttpServer.swift

@@ -8,11 +8,11 @@
 import Foundation
 
 public class HttpServer: HttpServerIO {
-    
+
     public static let VERSION = "1.4.7"
-    
+
     private let router = HttpRouter()
-    
+
     public override init() {
         self.DELETE = MethodRoute(method: "DELETE", router: router)
         self.PATCH  = MethodRoute(method: "PATCH", router: router)
@@ -20,7 +20,7 @@ public class HttpServer: HttpServerIO {
         self.POST   = MethodRoute(method: "POST", router: router)
         self.GET    = MethodRoute(method: "GET", router: router)
         self.PUT    = MethodRoute(method: "PUT", router: router)
-        
+
         self.delete = MethodRoute(method: "DELETE", router: router)
         self.patch  = MethodRoute(method: "PATCH", router: router)
         self.head   = MethodRoute(method: "HEAD", router: router)
@@ -28,23 +28,23 @@ public class HttpServer: HttpServerIO {
         self.get    = MethodRoute(method: "GET", router: router)
         self.put    = MethodRoute(method: "PUT", router: router)
     }
-    
+
     public var DELETE, PATCH, HEAD, POST, GET, PUT: MethodRoute
     public var delete, patch, head, post, get, put: MethodRoute
-    
+
     public subscript(path: String) -> ((HttpRequest) -> HttpResponse)? {
         set {
             router.register(nil, path: path, handler: newValue)
         }
         get { return nil }
     }
-    
+
     public var routes: [String] {
         return router.routes()
     }
-    
+
     public var notFoundHandler: ((HttpRequest) -> HttpResponse)?
-    
+
     public var middleware = [(HttpRequest) -> HttpResponse?]()
 
     override public func dispatch(_ request: HttpRequest) -> ([String: String], (HttpRequest) -> HttpResponse) {
@@ -61,7 +61,7 @@ public class HttpServer: HttpServerIO {
         }
         return super.dispatch(request)
     }
-    
+
     public struct MethodRoute {
         public let method: String
         public let router: HttpRouter

+ 3 - 3
XCode/Sources/HttpServerIO.swift

@@ -85,9 +85,9 @@ public class HttpServerIO {
                     strongSelf.queue.async {
                         strongSelf.sockets.insert(socket)
                     }
-                    
+
                     strongSelf.handleConnection(socket)
-                    
+
                     strongSelf.queue.async {
                         strongSelf.sockets.remove(socket)
                     }
@@ -172,7 +172,7 @@ public class HttpServerIO {
 
         // Some web-socket clients (like Jetfire) expects to have header section in a single packet.
         // We can't promise that but make sure we invoke "write" only once for response header section.
-        
+
         var responseHeader = String()
 
         responseHeader.append("HTTP/1.1 \(response.statusCode) \(response.reasonPhrase)\r\n")

+ 4 - 4
XCode/Sources/Process.swift

@@ -8,11 +8,11 @@
 import Foundation
 
 public class Process {
-    
+
     public static var pid: Int {
         return Int(getpid())
     }
-    
+
     public static var tid: UInt64 {
         #if os(Linux)
             return UInt64(pthread_self())
@@ -22,10 +22,10 @@ public class Process {
             return UInt64(tid)
         #endif
     }
-    
+
     private static var signalsWatchers = [(Int32) -> Void]()
     private static var signalsObserved = false
-    
+
     public static func watchSignals(_ callback: @escaping (Int32) -> Void) {
         if !signalsObserved {
             [SIGTERM, SIGHUP, SIGSTOP, SIGINT].forEach { item in

+ 4 - 4
XCode/Sources/Socket+File.swift

@@ -10,7 +10,7 @@ import Foundation
 #if os(iOS) || os(tvOS) || os (Linux)
 // swiftlint:disable type_name function_parameter_count
     struct sf_hdtr { }
-    
+
     private func sendfileImpl(_ source: UnsafeMutablePointer<FILE>, _ target: Int32, _: off_t, _: UnsafeMutablePointer<off_t>, _: UnsafeMutablePointer<sf_hdtr>, _: Int32) -> Int32 {
         var buffer = [UInt8](repeating: 0, count: 1024)
         while true {
@@ -35,17 +35,17 @@ import Foundation
 #endif
 
 extension Socket {
-    
+
     public func writeFile(_ file: String.File) throws {
         var offset: off_t = 0
         var sf: sf_hdtr = sf_hdtr()
-        
+
         #if os(iOS) || os(tvOS) || os (Linux)
         let result = sendfileImpl(file.pointer, self.socketFileDescriptor, 0, &offset, &sf, 0)
         #else
         let result = sendfile(fileno(file.pointer), self.socketFileDescriptor, 0, &offset, &sf, 0)
         #endif
-        
+
         if result == -1 {
             throw SocketError.writeFailed("sendfile: " + Errno.description())
         }

+ 1 - 1
XCode/Sources/Socket+Server.swift

@@ -102,7 +102,7 @@ extension Socket {
         }
         return Socket(socketFileDescriptor: socketFileDescriptor)
     }
-    
+
     public func acceptClientSocket() throws -> Socket {
         var addr = sockaddr()
         var len: socklen_t = 0

+ 18 - 18
XCode/Sources/Socket.swift

@@ -23,22 +23,22 @@ public enum SocketError: Error {
 
 // swiftlint: disable identifier_name
 open class Socket: Hashable, Equatable {
-        
+
     let socketFileDescriptor: Int32
     private var shutdown = false
 
     public init(socketFileDescriptor: Int32) {
         self.socketFileDescriptor = socketFileDescriptor
     }
-    
+
     deinit {
         close()
     }
-    
+
     public func hash(into hasher: inout Hasher) {
         hasher.combine(self.socketFileDescriptor)
     }
-    
+
     public func close() {
         if shutdown {
             return
@@ -46,7 +46,7 @@ open class Socket: Hashable, Equatable {
         shutdown = true
         Socket.close(self.socketFileDescriptor)
     }
-    
+
     public func port() throws -> in_port_t {
         var addr = sockaddr_in()
         return try withUnsafePointer(to: &addr) { pointer in
@@ -62,7 +62,7 @@ open class Socket: Hashable, Equatable {
             #endif
         }
     }
-    
+
     public func isIPv4() throws -> Bool {
         var addr = sockaddr_in()
         return try withUnsafePointer(to: &addr) { pointer in
@@ -73,15 +73,15 @@ open class Socket: Hashable, Equatable {
             return Int32(pointer.pointee.sin_family) == AF_INET
         }
     }
-    
+
     public func writeUTF8(_ string: String) throws {
         try writeUInt8(ArraySlice(string.utf8))
     }
-    
+
     public func writeUInt8(_ data: [UInt8]) throws {
         try writeUInt8(ArraySlice(data))
     }
-    
+
     public func writeUInt8(_ data: ArraySlice<UInt8>) throws {
         try data.withUnsafeBufferPointer {
             try writeBuffer($0.baseAddress!, length: data.count)
@@ -91,7 +91,7 @@ open class Socket: Hashable, Equatable {
     public func writeData(_ data: NSData) throws {
         try writeBuffer(data.bytes, length: data.length)
     }
-    
+
     public func writeData(_ data: Data) throws {
         #if compiler(>=5.0)
         try data.withUnsafeBytes { (body: UnsafeRawBufferPointer) -> Void in
@@ -121,7 +121,7 @@ open class Socket: Hashable, Equatable {
             sent += result
         }
     }
-    
+
     /// Read a single byte off the socket. This method is optimized for reading
     /// a single byte. For reading multiple bytes, use read(length:), which will
     /// pre-allocate heap space and read directly into it.
@@ -136,7 +136,7 @@ open class Socket: Hashable, Equatable {
 	    #else
 	    let count = Darwin.read(self.socketFileDescriptor as Int32, &byte, 1)
 	    #endif
-        
+
         guard count > 0 else {
             throw SocketError.recvFailed(Errno.description())
         }
@@ -179,7 +179,7 @@ open class Socket: Hashable, Equatable {
 	        #else
 	        let bytesRead = Darwin.read(self.socketFileDescriptor as Int32, baseAddress + offset, readLength)
 	        #endif
-            
+
             guard bytesRead > 0 else {
                 throw SocketError.recvFailed(Errno.description())
             }
@@ -189,10 +189,10 @@ open class Socket: Hashable, Equatable {
 
         return offset
     }
-    
+
     private static let CR: UInt8 = 13
     private static let NL: UInt8 = 10
-    
+
     public func readLine() throws -> String {
         var characters: String = ""
         var index: UInt8 = 0
@@ -202,7 +202,7 @@ open class Socket: Hashable, Equatable {
         } while index != Socket.NL
         return characters
     }
-    
+
     public func peername() throws -> String {
         var addr = sockaddr(), len: socklen_t = socklen_t(MemoryLayout<sockaddr>.size)
         if getpeername(self.socketFileDescriptor, &addr, &len) != 0 {
@@ -214,7 +214,7 @@ open class Socket: Hashable, Equatable {
         }
         return String(cString: hostBuffer)
     }
-    
+
     public class func setNoSigPipe(_ socket: Int32) {
         #if os(Linux)
             // There is no SO_NOSIGPIPE in Linux (nor some other systems). You can instead use the MSG_NOSIGNAL flag when calling send(),
@@ -225,7 +225,7 @@ open class Socket: Hashable, Equatable {
             setsockopt(socket, SOL_SOCKET, SO_NOSIGPIPE, &no_sig_pipe, socklen_t(MemoryLayout<Int32>.size))
         #endif
     }
-    
+
     public class func close(_ socket: Int32) {
         #if os(Linux)
             _ = Glibc.close(socket)

+ 1 - 1
XCode/Sources/String+BASE64.swift

@@ -8,7 +8,7 @@
 import Foundation
 
 extension String {
-    
+
     public static func toBase64(_ data: [UInt8]) -> String {
         return Data(data).base64EncodedString()
     }

+ 18 - 18
XCode/Sources/String+File.swift

@@ -8,27 +8,27 @@
 import Foundation
 
 extension String {
-    
+
     public enum FileError: Error {
         case error(Int32)
     }
-    
+
     public class File {
-        
+
         let pointer: UnsafeMutablePointer<FILE>
-        
+
         public init(_ pointer: UnsafeMutablePointer<FILE>) {
             self.pointer = pointer
         }
-        
+
         public func close() {
             fclose(pointer)
         }
-        
+
         public func seek(_ offset: Int) -> Bool {
             return (fseek(pointer, offset, SEEK_SET) == 0)
         }
-        
+
         public func read(_ data: inout [UInt8]) throws -> Int {
             if data.count <= 0 {
                 return data.count
@@ -45,7 +45,7 @@ extension String {
             }
             throw FileError.error(0)
         }
-        
+
         public func write(_ data: [UInt8]) throws {
             if data.count <= 0 {
                 return
@@ -56,7 +56,7 @@ extension String {
                 }
             }
         }
-        
+
         public static func currentWorkingDirectory() throws -> String {
             guard let path = getcwd(nil, 0) else {
                 throw FileError.error(errno)
@@ -64,28 +64,28 @@ extension String {
             return String(cString: path)
         }
     }
-    
+
     public static var pathSeparator = "/"
-    
+
     public func openNewForWriting() throws -> File {
         return try openFileForMode(self, "wb")
     }
-    
+
     public func openForReading() throws -> File {
         return try openFileForMode(self, "rb")
     }
-    
+
     public func openForWritingAndReading() throws -> File {
         return try openFileForMode(self, "r+b")
     }
-    
+
     public func openFileForMode(_ path: String, _ mode: String) throws -> File {
         guard let file = path.withCString({ pathPointer in mode.withCString({ fopen(pathPointer, $0) }) }) else {
             throw FileError.error(errno)
         }
         return File(file)
     }
-    
+
     public func exists() throws -> Bool {
         return try self.withStat {
             if $0 != nil {
@@ -94,7 +94,7 @@ extension String {
             return false
         }
     }
-    
+
     public func directory() throws -> Bool {
         return try self.withStat {
             if let stat = $0 {
@@ -103,7 +103,7 @@ extension String {
             return false
         }
     }
-    
+
     public func files() throws -> [String] {
         guard let dir = self.withCString({ opendir($0) }) else {
             throw FileError.error(errno)
@@ -131,7 +131,7 @@ extension String {
         }
         return results
     }
-    
+
     private func withStat<T>(_ closure: ((stat?) throws -> T)) throws -> T {
         return try self.withCString({
             var statBuffer = stat()

+ 2 - 2
XCode/Sources/String+Misc.swift

@@ -8,7 +8,7 @@
 import Foundation
 
 extension String {
-    
+
     public func unquote() -> String {
         var scalars = self.unicodeScalars
         if scalars.first == "\"" && scalars.last == "\"" && scalars.count >= 2 {
@@ -21,7 +21,7 @@ extension String {
 }
 
 extension UnicodeScalar {
-    
+
     public func asWhitespace() -> UInt8? {
         if self.value >= 9 && self.value <= 13 {
             return UInt8(self.value)

+ 31 - 31
XCode/Sources/String+SHA1.swift

@@ -9,68 +9,68 @@ import Foundation
 
 // swiftlint:disable identifier_name function_body_length
 public struct SHA1 {
-    
+
     public static func hash(_ input: [UInt8]) -> [UInt8] {
-        
+
         // Alghorithm from: https://en.wikipedia.org/wiki/SHA-1
-        
+
         var message = input
-        
+
         var h0 = UInt32(littleEndian: 0x67452301)
         var h1 = UInt32(littleEndian: 0xEFCDAB89)
         var h2 = UInt32(littleEndian: 0x98BADCFE)
         var h3 = UInt32(littleEndian: 0x10325476)
         var h4 = UInt32(littleEndian: 0xC3D2E1F0)
-        
+
         // ml = message length in bits (always a multiple of the number of bits in a character).
-        
+
         let ml = UInt64(message.count * 8)
-        
+
         // append the bit '1' to the message e.g. by adding 0x80 if message length is a multiple of 8 bits.
-        
+
         message.append(0x80)
-        
+
         // append 0 ≤ k < 512 bits '0', such that the resulting message length in bits is congruent to −64 ≡ 448 (mod 512)
-        
+
         let padBytesCount = ( message.count + 8 ) % 64
-        
+
         message.append(contentsOf: [UInt8](repeating: 0, count: 64 - padBytesCount))
-        
+
         // append ml, in a 64-bit big-endian integer. Thus, the total length is a multiple of 512 bits.
-        
+
         var mlBigEndian = ml.bigEndian
         withUnsafePointer(to: &mlBigEndian) {
             message.append(contentsOf: Array(UnsafeBufferPointer<UInt8>(start: UnsafePointer(OpaquePointer($0)), count: 8)))
         }
-        
+
         // Process the message in successive 512-bit chunks ( 64 bytes chunks ):
-        
+
         for chunkStart in 0..<message.count/64 {
             var words = [UInt32]()
             let chunk = message[chunkStart*64..<chunkStart*64+64]
-            
+
             // break chunk into sixteen 32-bit big-endian words w[i], 0 ≤ i ≤ 15
-            
+
             for index in 0...15 {
                 let value = chunk.withUnsafeBufferPointer({ UnsafePointer<UInt32>(OpaquePointer($0.baseAddress! + (index*4))).pointee})
                 words.append(value.bigEndian)
             }
-            
+
             // Extend the sixteen 32-bit words into eighty 32-bit words:
-            
+
             for index in 16...79 {
                 let value: UInt32 = ((words[index-3]) ^ (words[index-8]) ^ (words[index-14]) ^ (words[index-16]))
                 words.append(rotateLeft(value, 1))
             }
-            
+
             // Initialize hash value for this chunk:
-            
+
             var a = h0
             var b = h1
             var c = h2
             var d = h3
             var e = h4
-            
+
             for i in 0..<80 {
                 var f = UInt32(0)
                 var k = UInt32(0)
@@ -96,41 +96,41 @@ public struct SHA1 {
                 b = a
                 a = temp
             }
-            
+
             // Add this chunk's hash to result so far:
-            
+
             h0 = ( h0 &+ a ) & 0xFFFFFFFF
             h1 = ( h1 &+ b ) & 0xFFFFFFFF
             h2 = ( h2 &+ c ) & 0xFFFFFFFF
             h3 = ( h3 &+ d ) & 0xFFFFFFFF
             h4 = ( h4 &+ e ) & 0xFFFFFFFF
         }
-        
+
         // Produce the final hash value (big-endian) as a 160 bit number:
-        
+
         var digest = [UInt8]()
-        
+
         [h0, h1, h2, h3, h4].forEach { value in
             var bigEndianVersion = value.bigEndian
             withUnsafePointer(to: &bigEndianVersion) {
                 digest.append(contentsOf: Array(UnsafeBufferPointer<UInt8>(start: UnsafePointer(OpaquePointer($0)), count: 4)))
             }
         }
-        
+
         return digest
     }
-    
+
     private static func rotateLeft(_ v: UInt32, _ n: UInt32) -> UInt32 {
         return ((v << n) & 0xFFFFFFFF) | (v >> (32 - n))
     }
 }
 
 extension String {
-    
+
     public func sha1() -> [UInt8] {
         return SHA1.hash([UInt8](self.utf8))
     }
-    
+
     public func sha1() -> String {
         return self.sha1().reduce("") { $0 + String(format: "%02x", $1) }
     }

+ 18 - 18
XCode/Sources/WebSockets.swift

@@ -35,7 +35,7 @@ public func websocket(
             let session = WebSocketSession(socket)
             var fragmentedOpCode = WebSocketSession.OpCode.close
             var payload = [UInt8]() // Used for fragmented frames.
-            
+
             func handleTextPayload(_ frame: WebSocketSession.Frame) throws {
                 if let handleText = text {
                     if frame.fin {
@@ -55,7 +55,7 @@ public func websocket(
                     }
                 }
             }
-            
+
             func handleBinaryPayload(_ frame: WebSocketSession.Frame) throws {
                 if let handleBinary = binary {
                     if frame.fin {
@@ -69,7 +69,7 @@ public func websocket(
                     }
                 }
             }
-            
+
             func handleOperationCode(_ frame: WebSocketSession.Frame) throws {
                 switch frame.opcode {
                 case .continue:
@@ -105,16 +105,16 @@ public func websocket(
                     }
                 }
             }
-            
+
             func read() throws {
                 while true {
                     let frame = try session.readFrame()
                     try handleOperationCode(frame)
                 }
             }
-            
+
             connected?(session)
-            
+
             do {
                 try read()
             } catch let error {
@@ -136,7 +136,7 @@ public func websocket(
                 // If an error occurs, send the close handshake.
                 session.writeCloseFrame()
             }
-            
+
             disconnected?(session)
         }
         let secWebSocketAccept = String.toBase64((secWebSocketKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").sha1())
@@ -146,11 +146,11 @@ public func websocket(
 }
 
 public class WebSocketSession: Hashable, Equatable {
-    
+
     public enum WsError: Error { case unknownOpCode(String), unMaskedFrame(String), protocolError(String), invalidUTF8(String) }
     public enum OpCode: UInt8 { case `continue` = 0x00, close = 0x08, ping = 0x09, pong = 0x0A, text = 0x01, binary = 0x02 }
     public enum Control: Error { case close }
-    
+
     public class Frame {
         public var opcode = OpCode.close
         public var fin = false
@@ -161,16 +161,16 @@ public class WebSocketSession: Hashable, Equatable {
     }
 
     public let socket: Socket
-    
+
     public init(_ socket: Socket) {
         self.socket = socket
     }
-    
+
     deinit {
         writeCloseFrame()
         socket.close()
     }
-    
+
     public func writeText(_ text: String) {
         self.writeFrame(ArraySlice(text.utf8), OpCode.text)
     }
@@ -178,11 +178,11 @@ public class WebSocketSession: Hashable, Equatable {
     public func writeBinary(_ binary: [UInt8]) {
         self.writeBinary(ArraySlice(binary))
     }
-    
+
     public func writeBinary(_ binary: ArraySlice<UInt8>) {
         self.writeFrame(binary, OpCode.binary)
     }
-    
+
     public func writeFrame(_ data: ArraySlice<UInt8>, _ op: OpCode, _ fin: Bool = true) {
         let finAndOpCode = UInt8(fin ? 0x80 : 0x00) | op.rawValue
         let maskAndLngth = encodeLengthAndMaskFlag(UInt64(data.count), false)
@@ -194,11 +194,11 @@ public class WebSocketSession: Hashable, Equatable {
             print(error)
         }
     }
-    
+
     public func writeCloseFrame() {
         writeFrame(ArraySlice("".utf8), .close)
     }
-    
+
     private func encodeLengthAndMaskFlag(_ len: UInt64, _ masked: Bool) -> [UInt8] {
         let encodedLngth = UInt8(masked ? 0x80 : 0x00)
         var encodedBytes = [UInt8]()
@@ -222,7 +222,7 @@ public class WebSocketSession: Hashable, Equatable {
         }
         return encodedBytes
     }
-    
+
     // swiftlint:disable function_body_length
     public func readFrame() throws -> Frame {
         let frm = Frame()
@@ -284,7 +284,7 @@ public class WebSocketSession: Hashable, Equatable {
         }
         return frm
     }
-        
+
     public func hash(into hasher: inout Hasher) {
         hasher.combine(socket)
     }

+ 4 - 4
XCode/SwifterSampleOSX/main.swift

@@ -12,17 +12,17 @@ do {
     server["/testAfterBaseRoute"] = { request in
         return .ok(.htmlBody("ok !"))
     }
-    
+
     if #available(OSXApplicationExtension 10.10, *) {
         try server.start(9080, forceIPv4: true)
     } else {
         // Fallback on earlier versions
     }
-    
+
     print("Server has started ( port = \(try server.port()) ). Try to connect now...")
-    
+
     RunLoop.main.run()
-    
+
 } catch {
     print("Server start error: \(error)")
 }

+ 1 - 1
XCode/SwifterSampleiOS/AppDelegate.swift

@@ -10,7 +10,7 @@ import Swifter
 
 @UIApplicationMain
 class AppDelegate: UIResponder, UIApplicationDelegate {
-    
+
     var window: UIWindow?
     func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
         return true

+ 3 - 3
XCode/SwifterSampleiOS/ViewController.swift

@@ -8,9 +8,9 @@ import UIKit
 import Swifter
 
 class ViewController: UIViewController {
-    
+
     private var server: HttpServer?
-    
+
     override func viewDidLoad() {
         super.viewDidLoad()
         do {
@@ -21,7 +21,7 @@ class ViewController: UIViewController {
             print("Server start error: \(error)")
         }
     }
-    
+
     @IBAction func likedThis(_ sender: UIButton) {
         self.server?.stop()
         self.server = nil

+ 3 - 3
XCode/Tests/IOSafetyTests.swift

@@ -18,15 +18,15 @@ class IOSafetyTests: XCTestCase {
         server = HttpServer.pingServer()
         urlSession = URLSession(configuration: .default)
     }
-    
+
     override func tearDown() {
         if server.operating {
             server.stop()
         }
-        
+
         urlSession = nil
         server = nil
-        
+
         super.tearDown()
     }
 

+ 4 - 4
XCode/Tests/MimeTypesTests.swift

@@ -15,11 +15,11 @@ class MimeTypeTests: XCTestCase {
         XCTAssertNotNil(NSURL.mimeType, "Type NSURL is extended with mimeType")
         XCTAssertNotNil(NSString.mimeType, "Type NSString is extended with mimeType")
     }
-    
+
     func testDefaultValue() {
         XCTAssertEqual("file.null".mimeType(), "application/octet-stream")
     }
-    
+
     func testCorrectTypes() {
         XCTAssertEqual("file.html".mimeType(), "text/html")
         XCTAssertEqual("file.css".mimeType(), "text/css")
@@ -27,7 +27,7 @@ class MimeTypeTests: XCTestCase {
         XCTAssertEqual("file.pptx".mimeType(), "application/vnd.openxmlformats-officedocument.presentationml.presentation")
         XCTAssertEqual("file.war".mimeType(), "application/java-archive")
     }
-    
+
     func testCaseInsensitivity() {
         XCTAssertEqual("file.HTML".mimeType(), "text/html")
         XCTAssertEqual("file.cSs".mimeType(), "text/css")
@@ -35,5 +35,5 @@ class MimeTypeTests: XCTestCase {
         XCTAssertEqual("file.PPTX".mimeType(), "application/vnd.openxmlformats-officedocument.presentationml.presentation")
         XCTAssertEqual("FILE.WAR".mimeType(), "application/java-archive")
     }
-  
+
 }

+ 5 - 5
XCode/Tests/PingServer.swift

@@ -30,7 +30,7 @@ extension URLSession {
     ) -> URLSessionDataTask {
         return self.dataTask(with: hostURL.appendingPathComponent("/ping"), completionHandler: handler)
     }
-    
+
     func retryPing(
         hostURL: URL = defaultLocalhost,
         timeout: Double = 2.0
@@ -44,22 +44,22 @@ extension URLSession {
                 timedOut = true
                 break
             }
-            
+
             #if swift(>=4.2)
             let mode = RunLoop.Mode.common
             #else
             let mode = RunLoopMode.commonModes
             #endif
-            
+
             _ = RunLoop.current.run(
                 mode: mode,
                 before: NSDate.distantFuture
             )
         }
-        
+
         return timedOut
     }
-    
+
     func signalIfPongReceived(_ semaphore: DispatchSemaphore, hostURL: URL) {
         pingTask(hostURL: hostURL) { _, response, _ in
             if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {

+ 25 - 25
XCode/Tests/ServerThreadingTests.swift

@@ -10,14 +10,14 @@ import XCTest
 @testable import Swifter
 
 class ServerThreadingTests: XCTestCase {
-    
+
     var server: HttpServer!
-    
+
     override func setUp() {
         super.setUp()
         server = HttpServer()
     }
-    
+
     override func tearDown() {
         if server.operating {
             server.stop()
@@ -25,17 +25,17 @@ class ServerThreadingTests: XCTestCase {
         server = nil
         super.tearDown()
     }
-    
+
     func testShouldHandleTheSameRequestWithDifferentTimeIntervals() {
-        
+
         let path = "/a/:b/c"
         let queue = DispatchQueue(label: "com.swifter.threading")
         let hostURL: URL
-        
+
         server.GET[path] = { .ok(.htmlBody("You asked for " + $0.path)) }
-        
+
         do {
-            
+
             #if os(Linux)
             try server.start(9081)
             hostURL = URL(string: "http://localhost:9081")!
@@ -43,10 +43,10 @@ class ServerThreadingTests: XCTestCase {
             try server.start()
             hostURL = defaultLocalhost
             #endif
-            
+
             let requestExpectation = expectation(description: "Request should finish.")
             requestExpectation.expectedFulfillmentCount = 3
-            
+
             (1...3).forEach { index in
                 queue.asyncAfter(deadline: .now() + .seconds(index)) {
                     let task = URLSession.shared.executeAsyncTask(hostURL: hostURL, path: path) { (_, response, _ ) in
@@ -55,35 +55,35 @@ class ServerThreadingTests: XCTestCase {
                         XCTAssertNotNil(statusCode)
                         XCTAssertEqual(statusCode, 200, "\(hostURL)")
                     }
-                    
+
                     task.resume()
                 }
             }
-            
+
         } catch let error {
             XCTFail("\(error)")
         }
-        
+
         waitForExpectations(timeout: 10, handler: nil)
     }
-    
+
     func testShouldHandleTheSameRequestConcurrently() {
-        
+
         let path = "/a/:b/c"
         server.GET[path] = { .ok(.htmlBody("You asked for " + $0.path)) }
-        
+
         var requestExpectation: XCTestExpectation? = expectation(description: "Should handle the request concurrently")
-        
+
         do {
-            
+
             try server.start()
             let downloadGroup = DispatchGroup()
-            
+
             DispatchQueue.concurrentPerform(iterations: 3) { _ in
                 downloadGroup.enter()
-                
+
                 let task = URLSession.shared.executeAsyncTask(path: path) { (_, response, _ ) in
-                    
+
                     let statusCode = (response as? HTTPURLResponse)?.statusCode
                     XCTAssertNotNil(statusCode)
                     XCTAssertEqual(statusCode, 200)
@@ -91,20 +91,20 @@ class ServerThreadingTests: XCTestCase {
                     requestExpectation = nil
                     downloadGroup.leave()
                 }
-                
+
                 task.resume()
             }
-            
+
         } catch let error {
             XCTFail("\(error)")
         }
-        
+
         waitForExpectations(timeout: 15, handler: nil)
     }
 }
 
 extension URLSession {
-    
+
     func executeAsyncTask(
         hostURL: URL = defaultLocalhost,
         path: String,

+ 18 - 18
XCode/Tests/SwifterTestsHttpParser.swift

@@ -9,7 +9,7 @@ import XCTest
 @testable import Swifter
 
 class SwifterTestsHttpParser: XCTestCase {
-    
+
     /// A specialized Socket which creates a linked socket pair with a pipe, and
     /// immediately writes in fixed data. This enables tests to static fixture
     /// data into the regular Socket flow.
@@ -45,7 +45,7 @@ class SwifterTestsHttpParser: XCTestCase {
             #else
             Darwin.close(fdWrite) // the super instance will close fdRead in deinit!
             #endif
-            
+
             super.init(socketFileDescriptor: fdRead)
         }
     }
@@ -53,60 +53,60 @@ class SwifterTestsHttpParser: XCTestCase {
     // swiftlint:disable function_body_length
     func testParser() {
         let parser = HttpParser()
-        
+
         do {
             _ = try parser.readHttpRequest(TestSocket(""))
             XCTAssert(false, "Parser should throw an error if socket is empty.")
         } catch { }
-        
+
         do {
             _ = try parser.readHttpRequest(TestSocket("12345678"))
             XCTAssert(false, "Parser should throw an error if status line has single token.")
         } catch { }
-        
+
         do {
             _ = try parser.readHttpRequest(TestSocket("GET HTTP/1.0"))
             XCTAssert(false, "Parser should throw an error if status line has not enough tokens.")
         } catch { }
-        
+
         do {
             _ = try parser.readHttpRequest(TestSocket("GET / HTTP/1.0"))
             XCTAssert(false, "Parser should throw an error if there is no next line symbol.")
         } catch { }
-        
+
         do {
             _ = try parser.readHttpRequest(TestSocket("GET / HTTP/1.0"))
             XCTAssert(false, "Parser should throw an error if there is no next line symbol.")
         } catch { }
-        
+
         do {
             _ = try parser.readHttpRequest(TestSocket("GET / HTTP/1.0\r"))
             XCTAssert(false, "Parser should throw an error if there is no next line symbol.")
         } catch { }
-        
+
         do {
             _ = try parser.readHttpRequest(TestSocket("GET / HTTP/1.0\n"))
             XCTAssert(false, "Parser should throw an error if there is no 'Content-Length' header.")
         } catch { }
-        
+
         do {
             _ = try parser.readHttpRequest(TestSocket("GET / HTTP/1.0\r\nContent-Length: 0\r\n\r\n"))
         } catch {
             XCTAssert(false, "Parser should not throw any errors if there is a valid 'Content-Length' header.")
         }
-        
+
         do {
             _ = try parser.readHttpRequest(TestSocket("GET / HTTP/1.0\nContent-Length: 0\r\n\n"))
         } catch {
             XCTAssert(false, "Parser should not throw any errors if there is a valid 'Content-Length' header.")
         }
-        
+
         do {
             _ = try parser.readHttpRequest(TestSocket("GET / HTTP/1.0\nContent-Length: 5\n\n12345"))
         } catch {
             XCTAssert(false, "Parser should not throw any errors if there is a valid 'Content-Length' header.")
         }
-        
+
         do {
             _ = try parser.readHttpRequest(TestSocket("GET / HTTP/1.0\nContent-Length: 10\r\n\n"))
             XCTAssert(false, "Parser should throw an error if request' body is too short.")
@@ -148,20 +148,20 @@ class SwifterTestsHttpParser: XCTestCase {
             let unicodeBytes = bodyString.utf8.map { return $0 }
             XCTAssert(request.body == unicodeBytes, "Request body must be correct")
         } catch { }
-        
+
         var resp = try? parser.readHttpRequest(TestSocket("GET /open?link=https://www.youtube.com/watch?v=D2cUBG4PnOA HTTP/1.0\nContent-Length: 10\n\n1234567890"))
-        
+
         XCTAssertEqual(resp?.queryParams.filter({ $0.0 == "link"}).first?.1, "https://www.youtube.com/watch?v=D2cUBG4PnOA")
         XCTAssertEqual(resp?.method, "GET", "Parser should extract HTTP method name from the status line.")
         XCTAssertEqual(resp?.path, "/open", "Parser should extract HTTP path value from the status line.")
         XCTAssertEqual(resp?.headers["content-length"], "10", "Parser should extract Content-Length header value.")
-        
+
         resp = try? parser.readHttpRequest(TestSocket("POST / HTTP/1.0\nContent-Length: 10\n\n1234567890"))
         XCTAssertEqual(resp?.method, "POST", "Parser should extract HTTP method name from the status line.")
-        
+
         resp = try? parser.readHttpRequest(TestSocket("GET / HTTP/1.0\nHeader1: 1:1:34\nHeader2: 12345\nContent-Length: 0\n\n"))
         XCTAssertEqual(resp?.headers["header1"], "1:1:34", "Parser should properly extract header name and value in case the value has ':' character.")
-        
+
         resp = try? parser.readHttpRequest(TestSocket("GET / HTTP/1.0\nHeader1: 1\nHeader2: 2\nContent-Length: 0\n\n"))
         XCTAssertEqual(resp?.headers["header1"], "1", "Parser should extract multiple headers from the request.")
         XCTAssertEqual(resp?.headers["header2"], "2", "Parser should extract multiple headers from the request.")

+ 8 - 8
XCode/Tests/SwifterTestsHttpResponseBody.swift

@@ -7,35 +7,35 @@ import XCTest
 @testable import Swifter
 
 class SwifterTestsHttpResponseBody: XCTestCase {
-    
+
     func testDictionaryAsJSONPayload() {
         verify(input: ["key": "value"], output: "{\"key\":\"value\"}")
         verify(input: ["key": ["value1", "value2", "value3"]], output: "{\"key\":[\"value1\",\"value2\",\"value3\"]}")
     }
-    
+
     func testArrayAsJSONPayload() {
         verify(input: ["key", "value"], output: "[\"key\",\"value\"]")
         verify(input: ["value1", "value2", "value3"], output: "[\"value1\",\"value2\",\"value3\"]")
     }
-    
+
     func testNSDictionaryAsJSONPayload() {
         verify(input: ["key": "value"] as NSDictionary, output: "{\"key\":\"value\"}")
         verify(input: ["key": ["value1", "value2", "value3"]] as NSDictionary, output: "{\"key\":[\"value1\",\"value2\",\"value3\"]}")
     }
-    
+
     func testNSArrayAsJSONPayload() {
         verify(input: ["key", "value"] as NSArray, output: "[\"key\",\"value\"]")
         verify(input: ["value1", "value2", "value3"] as NSArray, output: "[\"value1\",\"value2\",\"value3\"]")
     }
-    
+
     private func verify(input: Any, output expectedOutput: String, line: UInt = #line) {
         let response: HttpResponseBody = .json(input)
-        
+
         guard let writer = response.content().1 else {
             XCTFail(line: line)
             return
         }
-        
+
         do {
             let mockWriter = MockWriter()
             try writer(mockWriter)
@@ -49,7 +49,7 @@ class SwifterTestsHttpResponseBody: XCTestCase {
 
 private class MockWriter: HttpResponseBodyWriter {
     var data = Data()
-    
+
     func write(_ file: String.File) throws { }
     func write(_ data: [UInt8]) throws { }
     func write(_ data: ArraySlice<UInt8>) throws { }

+ 57 - 57
XCode/Tests/SwifterTestsHttpRouter.swift

@@ -10,47 +10,47 @@ import XCTest
 @testable import Swifter
 
 class SwifterTestsHttpRouter: XCTestCase {
-    
+
     var router: HttpRouter!
-    
+
     override func setUp() {
         super.setUp()
         router = HttpRouter()
     }
-    
+
     override func tearDown() {
         router = nil
         super.tearDown()
     }
-    
+
     func testHttpRouterSlashRoot() {
-        
+
         router.register(nil, path: "/", handler: { _ in
             return .ok(.htmlBody("OK"))
         })
-        
+
         XCTAssertNotNil(router.route(nil, path: "/"))
     }
-    
+
     func testHttpRouterSimplePathSegments() {
-        
+
         router.register(nil, path: "/a/b/c/d", handler: { _ in
             return .ok(.htmlBody("OK"))
         })
-        
+
         XCTAssertNil(router.route(nil, path: "/"))
         XCTAssertNil(router.route(nil, path: "/a"))
         XCTAssertNil(router.route(nil, path: "/a/b"))
         XCTAssertNil(router.route(nil, path: "/a/b/c"))
         XCTAssertNotNil(router.route(nil, path: "/a/b/c/d"))
     }
-    
+
     func testHttpRouterSinglePathSegmentWildcard() {
-        
+
         router.register(nil, path: "/a/*/c/d", handler: { _ in
             return .ok(.htmlBody("OK"))
         })
-        
+
         XCTAssertNil(router.route(nil, path: "/"))
         XCTAssertNil(router.route(nil, path: "/a"))
         XCTAssertNotNil(router.route(nil, path: "/a/foo/c/d"))
@@ -58,13 +58,13 @@ class SwifterTestsHttpRouter: XCTestCase {
         XCTAssertNil(router.route(nil, path: "/a/b"))
         XCTAssertNil(router.route(nil, path: "/a/b/foo/d"))
     }
-    
+
     func testHttpRouterVariables() {
-        
+
         router.register(nil, path: "/a/:arg1/:arg2/b/c/d/:arg3", handler: { _ in
             return .ok(.htmlBody("OK"))
         })
-        
+
         XCTAssertNil(router.route(nil, path: "/"))
         XCTAssertNil(router.route(nil, path: "/a"))
         XCTAssertNil(router.route(nil, path: "/a/b/c/d"))
@@ -72,54 +72,54 @@ class SwifterTestsHttpRouter: XCTestCase {
         XCTAssertEqual(router.route(nil, path: "/a/value1/value2/b/c/d/value3")?.0[":arg2"], "value2")
         XCTAssertEqual(router.route(nil, path: "/a/value1/value2/b/c/d/value3")?.0[":arg3"], "value3")
     }
-    
+
     func testHttpRouterMultiplePathSegmentWildcards() {
-        
+
         router.register(nil, path: "/a/**/e/f/g", handler: { _ in
             return .ok(.htmlBody("OK"))
         })
-        
+
         XCTAssertNil(router.route(nil, path: "/"))
         XCTAssertNil(router.route(nil, path: "/a"))
         XCTAssertNotNil(router.route(nil, path: "/a/b/c/d/e/f/g"))
         XCTAssertNil(router.route(nil, path: "/a/e/f/g"))
     }
-    
+
     func testHttpRouterEmptyTail() {
-        
+
         router.register(nil, path: "/a/b/", handler: { _ in
             return .ok(.htmlBody("OK"))
         })
-        
+
         router.register(nil, path: "/a/b/:var", handler: { _ in
             return .ok(.htmlBody("OK"))
         })
-        
+
         XCTAssertNil(router.route(nil, path: "/"))
         XCTAssertNil(router.route(nil, path: "/a"))
         XCTAssertNotNil(router.route(nil, path: "/a/b/"))
         XCTAssertNil(router.route(nil, path: "/a/e/f/g"))
-        
+
         XCTAssertEqual(router.route(nil, path: "/a/b/value1")?.0[":var"], "value1")
-        
+
         XCTAssertEqual(router.route(nil, path: "/a/b/")?.0[":var"], nil)
     }
-    
+
     func testHttpRouterPercentEncodedPathSegments() {
-        
+
         router.register(nil, path: "/a/<>/^", handler: { _ in
             return .ok(.htmlBody("OK"))
         })
-        
+
         XCTAssertNil(router.route(nil, path: "/"))
         XCTAssertNil(router.route(nil, path: "/a"))
         XCTAssertNotNil(router.route(nil, path: "/a/%3C%3E/%5E"))
     }
-    
+
     func testHttpRouterHandlesOverlappingPaths() {
-        
+
         let request = HttpRequest()
-        
+
         let staticRouteExpectation = expectation(description: "Static Route")
         var foundStaticRoute = false
         router.register("GET", path: "a/b") { _ in
@@ -127,7 +127,7 @@ class SwifterTestsHttpRouter: XCTestCase {
             staticRouteExpectation.fulfill()
             return HttpResponse.accepted
         }
-        
+
         let variableRouteExpectation = expectation(description: "Variable Route")
         var foundVariableRoute = false
         router.register("GET", path: "a/:id/c") { _ in
@@ -135,26 +135,26 @@ class SwifterTestsHttpRouter: XCTestCase {
             variableRouteExpectation.fulfill()
             return HttpResponse.accepted
         }
-        
+
         let staticRouteResult = router.route("GET", path: "a/b")
         let staticRouterHandler = staticRouteResult?.1
         XCTAssertNotNil(staticRouteResult)
         _ = staticRouterHandler?(request)
-        
+
         let variableRouteResult = router.route("GET", path: "a/b/c")
         let variableRouterHandler = variableRouteResult?.1
         XCTAssertNotNil(variableRouteResult)
         _ = variableRouterHandler?(request)
-        
+
         waitForExpectations(timeout: 10, handler: nil)
         XCTAssertTrue(foundStaticRoute)
         XCTAssertTrue(foundVariableRoute)
     }
-    
+
     func testHttpRouterHandlesOverlappingPathsInDynamicRoutes() {
-    
+
         let request = HttpRequest()
-        
+
         let firstVariableRouteExpectation = expectation(description: "First Variable Route")
         var foundFirstVariableRoute = false
         router.register("GET", path: "a/:id") { _ in
@@ -162,7 +162,7 @@ class SwifterTestsHttpRouter: XCTestCase {
             firstVariableRouteExpectation.fulfill()
             return HttpResponse.accepted
         }
-        
+
         let secondVariableRouteExpectation = expectation(description: "Second Variable Route")
         var foundSecondVariableRoute = false
         router.register("GET", path: "a/:id/c") { _ in
@@ -170,26 +170,26 @@ class SwifterTestsHttpRouter: XCTestCase {
             secondVariableRouteExpectation.fulfill()
             return HttpResponse.accepted
         }
-        
+
         let firstRouteResult = router.route("GET", path: "a/b")
         let firstRouterHandler = firstRouteResult?.1
         XCTAssertNotNil(firstRouteResult)
         _ = firstRouterHandler?(request)
-        
+
         let secondRouteResult = router.route("GET", path: "a/b/c")
         let secondRouterHandler = secondRouteResult?.1
         XCTAssertNotNil(secondRouteResult)
         _ = secondRouterHandler?(request)
-        
+
         waitForExpectations(timeout: 10, handler: nil)
         XCTAssertTrue(foundFirstVariableRoute)
         XCTAssertTrue(foundSecondVariableRoute)
     }
-    
+
     func testHttpRouterShouldHandleOverlappingRoutesInTrail() {
-        
+
         let request = HttpRequest()
-        
+
         let firstVariableRouteExpectation = expectation(description: "First Variable Route")
         var foundFirstVariableRoute = false
         router.register("GET", path: "/a/:id") { _ in
@@ -197,7 +197,7 @@ class SwifterTestsHttpRouter: XCTestCase {
             firstVariableRouteExpectation.fulfill()
             return HttpResponse.accepted
         }
-        
+
         let secondVariableRouteExpectation = expectation(description: "Second Variable Route")
         var foundSecondVariableRoute = false
         router.register("GET", path: "/a") { _ in
@@ -205,7 +205,7 @@ class SwifterTestsHttpRouter: XCTestCase {
             secondVariableRouteExpectation.fulfill()
             return HttpResponse.accepted
         }
-        
+
         let thirdVariableRouteExpectation = expectation(description: "Third Variable Route")
         var foundThirdVariableRoute = false
         router.register("GET", path: "/a/:id/b") { _ in
@@ -213,32 +213,32 @@ class SwifterTestsHttpRouter: XCTestCase {
             thirdVariableRouteExpectation.fulfill()
             return HttpResponse.accepted
         }
-        
+
         let firstRouteResult = router.route("GET", path: "/a")
         let firstRouterHandler = firstRouteResult?.1
         XCTAssertNotNil(firstRouteResult)
         _ = firstRouterHandler?(request)
-        
+
         let secondRouteResult = router.route("GET", path: "/a/b")
         let secondRouterHandler = secondRouteResult?.1
         XCTAssertNotNil(secondRouteResult)
         _ = secondRouterHandler?(request)
-        
+
         let thirdRouteResult = router.route("GET", path: "/a/b/b")
         let thirdRouterHandler = thirdRouteResult?.1
         XCTAssertNotNil(thirdRouteResult)
         _ = thirdRouterHandler?(request)
-        
+
         waitForExpectations(timeout: 10, handler: nil)
         XCTAssertTrue(foundFirstVariableRoute)
         XCTAssertTrue(foundSecondVariableRoute)
         XCTAssertTrue(foundThirdVariableRoute)
     }
-    
+
     func testHttpRouterHandlesOverlappingPathsInDynamicRoutesInTheMiddle() {
-        
+
         let request = HttpRequest()
-        
+
         let firstVariableRouteExpectation = expectation(description: "First Variable Route")
         var foundFirstVariableRoute = false
         router.register("GET", path: "/a/b/c/d/e") { _ in
@@ -246,7 +246,7 @@ class SwifterTestsHttpRouter: XCTestCase {
             firstVariableRouteExpectation.fulfill()
             return HttpResponse.accepted
         }
-        
+
         let secondVariableRouteExpectation = expectation(description: "Second Variable Route")
         var foundSecondVariableRoute = false
         router.register("GET", path: "/a/:id/f/g") { _ in
@@ -254,17 +254,17 @@ class SwifterTestsHttpRouter: XCTestCase {
             secondVariableRouteExpectation.fulfill()
             return HttpResponse.accepted
         }
-        
+
         let firstRouteResult = router.route("GET", path: "/a/b/c/d/e")
         let firstRouterHandler = firstRouteResult?.1
         XCTAssertNotNil(firstRouteResult)
         _ = firstRouterHandler?(request)
-        
+
         let secondRouteResult = router.route("GET", path: "/a/b/f/g")
         let secondRouterHandler = secondRouteResult?.1
         XCTAssertNotNil(secondRouteResult)
         _ = secondRouterHandler?(request)
-        
+
         waitForExpectations(timeout: 10, handler: nil)
         XCTAssertTrue(foundFirstVariableRoute)
         XCTAssertTrue(foundSecondVariableRoute)

+ 12 - 12
XCode/Tests/SwifterTestsStringExtensions.swift

@@ -8,18 +8,18 @@
 import XCTest
 
 class SwifterTestsStringExtensions: XCTestCase {
-    
+
     func testSHA1() {
         XCTAssertEqual("".sha1(), "da39a3ee5e6b4b0d3255bfef95601890afd80709")
         XCTAssertEqual("test".sha1(), "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3")
-        
+
         // Values copied from OpenSSL:
         // https://github.com/openssl/openssl/blob/master/test/sha1test.c
-        
+
         XCTAssertEqual("abc".sha1(), "a9993e364706816aba3e25717850c26c9cd0d89d")
         XCTAssertEqual("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".sha1(),
             "84983e441c3bd26ebaae4aa1f95129e5e54670f1")
-        
+
         XCTAssertEqual(
             ("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" +
              "a9993e364706816aba3e25717850c26c9cd0d89d" +
@@ -36,13 +36,13 @@ class SwifterTestsStringExtensions: XCTestCase {
              "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq").sha1(),
             "a377b0c42d685fdc396e29a9eda7101d900947ca")
     }
-    
+
     func testBASE64() {
         XCTAssertEqual(String.toBase64([UInt8]("".utf8)), "")
-        
+
         // Values copied from OpenSSL:
         // https://github.com/openssl/openssl/blob/995197ab84901df1cdf83509c4ce3511ea7f5ec0/test/evptests.txt
-        
+
         XCTAssertEqual(String.toBase64([UInt8]("h".utf8)), "aA==")
         XCTAssertEqual(String.toBase64([UInt8]("hello".utf8)), "aGVsbG8=")
         XCTAssertEqual(String.toBase64([UInt8]("hello world!".utf8)), "aGVsbG8gd29ybGQh")
@@ -51,22 +51,22 @@ class SwifterTestsStringExtensions: XCTestCase {
             "eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eA==")
         XCTAssertEqual(String.toBase64([UInt8]("h".utf8)), "aA==")
     }
-    
+
     func testMiscUnquote() {
         XCTAssertEqual("".unquote(), "")
         XCTAssertEqual("\"".unquote(), "\"")
         XCTAssertEqual("\"\"".unquote(), "")
-        
+
         XCTAssertEqual("1234".unquote(), "1234")
         XCTAssertEqual("1234\"".unquote(), "1234\"")
         XCTAssertEqual("\"1234".unquote(), "\"1234")
         XCTAssertEqual("\"1234\"".unquote(), "1234")
         XCTAssertEqual("\"1234\"".unquote(), "1234")
-        
+
         XCTAssertEqual("\"\"\"".unquote(), "\"")
         XCTAssertEqual("\"\" \"\"".unquote(), "\" \"")
     }
-    
+
     func testMiscTrim() {
         XCTAssertEqual("".trimmingCharacters(in: .whitespacesAndNewlines), "")
         XCTAssertEqual(" ".trimmingCharacters(in: .whitespacesAndNewlines), "")
@@ -84,7 +84,7 @@ class SwifterTestsStringExtensions: XCTestCase {
         XCTAssertEqual("t&e&s&t12%3%".replacingOccurrences(of: "&", with: "+").replacingOccurrences(of: "%", with: "+"), "t+e+s+t12+3+")
         XCTAssertEqual("test 1234 #$%^&*( test   ".replacingOccurrences(of: " ", with: "_"), "test_1234_#$%^&*(_test___")
     }
-    
+
     func testMiscRemovePercentEncoding() {
         XCTAssertEqual("".removingPercentEncoding!, "")
         XCTAssertEqual("%20".removingPercentEncoding!, " ")

+ 14 - 14
XCode/Tests/SwifterTestsWebSocketSession.swift

@@ -9,16 +9,16 @@ import XCTest
 @testable import Swifter
 
 class SwifterTestsWebSocketSession: XCTestCase {
-    
+
     class TestSocket: Socket {
         var content = [UInt8]()
         var offset = 0
-        
+
         init(_ content: [UInt8]) {
             super.init(socketFileDescriptor: -1)
             self.content.append(contentsOf: content)
         }
-        
+
         override func read() throws -> UInt8 {
             if offset < content.count {
                 let value = self.content[offset]
@@ -28,10 +28,10 @@ class SwifterTestsWebSocketSession: XCTestCase {
             throw SocketError.recvFailed("")
         }
     }
-    
+
     // swiftlint:disable function_body_length
     func testParser() {
-        
+
         do {
             let session = WebSocketSession(TestSocket([0]))
             _ = try session.readFrame()
@@ -39,7 +39,7 @@ class SwifterTestsWebSocketSession: XCTestCase {
         } catch {
             XCTAssert(true, "Parser should throw an error if socket has not enough data for a frame.")
         }
-        
+
         do {
             let session = WebSocketSession(TestSocket([0b0000_0001, 0b0000_0000, 0, 0, 0, 0]))
             _ = try session.readFrame()
@@ -49,7 +49,7 @@ class SwifterTestsWebSocketSession: XCTestCase {
         } catch {
             XCTAssert(false, "Parse should throw UnMaskedFrame error for unmasked message.")
         }
-        
+
         do {
             let session = WebSocketSession(TestSocket([0b1000_0001, 0b1000_0000, 0, 0, 0, 0]))
             let frame = try session.readFrame()
@@ -57,7 +57,7 @@ class SwifterTestsWebSocketSession: XCTestCase {
         } catch {
             XCTAssert(false, "Parser should not throw an error for a frame with fin flag set (\(error)")
         }
-        
+
         do {
             let session = WebSocketSession(TestSocket([0b0000_0000, 0b1000_0000, 0, 0, 0, 0]))
             let frame = try session.readFrame()
@@ -65,7 +65,7 @@ class SwifterTestsWebSocketSession: XCTestCase {
         } catch {
             XCTAssertTrue(true, "Parser should accept Continue opcode without any errors.")
         }
-        
+
         do {
             let session = WebSocketSession(TestSocket([0b0000_0001, 0b1000_0000, 0, 0, 0, 0]))
             let frame = try session.readFrame()
@@ -73,7 +73,7 @@ class SwifterTestsWebSocketSession: XCTestCase {
         } catch {
             XCTAssert(false, "Parser should accept Text opcode without any errors.")
         }
-        
+
         do {
             let session = WebSocketSession(TestSocket([0b0000_0010, 0b1000_0000, 0, 0, 0, 0]))
             let frame = try session.readFrame()
@@ -81,7 +81,7 @@ class SwifterTestsWebSocketSession: XCTestCase {
         } catch {
             XCTAssert(false, "Parser should accept Binary opcode without any errors.")
         }
-        
+
         do {
             let session = WebSocketSession(TestSocket([0b1000_1000, 0b1000_0000, 0, 0, 0, 0]))
             let frame = try session.readFrame()
@@ -89,7 +89,7 @@ class SwifterTestsWebSocketSession: XCTestCase {
         } catch let error {
             XCTAssert(false, "Parser should accept Close opcode without any errors. \(error)")
         }
-        
+
         do {
             let session = WebSocketSession(TestSocket([0b1000_1001, 0b1000_0000, 0, 0, 0, 0]))
             let frame = try session.readFrame()
@@ -97,7 +97,7 @@ class SwifterTestsWebSocketSession: XCTestCase {
         } catch let error {
             XCTAssert(false, "Parser should accept Ping opcode without any errors. \(error)")
         }
-        
+
         do {
             let session = WebSocketSession(TestSocket([0b1000_1010, 0b1000_0000, 0, 0, 0, 0]))
             let frame = try session.readFrame()
@@ -105,7 +105,7 @@ class SwifterTestsWebSocketSession: XCTestCase {
         } catch let error {
             XCTAssert(false, "Parser should accept Pong opcode without any errors. \(error)")
         }
-        
+
         for opcode in [3, 4, 5, 6, 7, 11, 12, 13, 14, 15] {
             do {
                 let session = WebSocketSession(TestSocket([UInt8(opcode), 0b1000_0000, 0, 0, 0, 0]))