Pārlūkot izejas kodu

Ready for XCode 8 Beta + Swift 3.0 Preview 3.

Damian Kołakowski 10 gadi atpakaļ
vecāks
revīzija
0c2e732655

+ 1 - 1
Sources/CSQLite/module.map

@@ -1,4 +1,4 @@
 module CSQLite {
     umbrella header "include/sqlite.h"
     export *
-}
+}

+ 1 - 1
Sources/Swifter/App.swift

@@ -14,7 +14,7 @@ public class App {
     public init() { }
     
     @available(OSX 10.10, *)
-    public func run(port: in_port_t = 9080, _ databasePath: String) throws -> Void {
+    public func run(_ port: in_port_t = 9080, _ databasePath: String) throws -> Void {
         
         // Open database connection.
         

+ 9 - 9
Sources/Swifter/DemoServer.swift

@@ -34,7 +34,7 @@ public func demoServer(_ publicDir: String) -> HttpServer {
         }
     }
     
-    server["/magic"] = { .OK(.Html("You asked for " + $0.path)) }
+    server["/magic"] = { .ok(.html("You asked for " + $0.path)) }
     
     server["/test/:param1/:param2"] = { r in
         scopes {
@@ -101,7 +101,7 @@ public func demoServer(_ publicDir: String) -> HttpServer {
         for multipart in r.parseMultiPartFormData() {
             response += "Name: \(multipart.name) File name: \(multipart.fileName) Size: \(multipart.body.count)<br>"
         }
-        return HttpResponse.OK(.Html(response))
+        return HttpResponse.ok(.html(response))
     }
     
     server.GET["/login"] = scopes {
@@ -139,7 +139,7 @@ public func demoServer(_ publicDir: String) -> HttpServer {
     
     server.POST["/login"] = { r in
         let formFields = r.parseUrlencodedForm()
-        return HttpResponse.OK(.Html(formFields.map({ "\($0.0) = \($0.1)" }).joined(separator: "<br>")))
+        return HttpResponse.ok(.html(formFields.map({ "\($0.0) = \($0.1)" }).joined(separator: "<br>")))
     }
     
     server["/demo"] = scopes {
@@ -154,25 +154,25 @@ public func demoServer(_ publicDir: String) -> HttpServer {
     }
     
     server["/raw"] = { r in
-        return HttpResponse.RAW(200, "OK", ["XXX-Custom-Header": "value"], { $0.write([UInt8]("test".utf8)) })
+        return HttpResponse.raw(200, "OK", ["XXX-Custom-Header": "value"], { $0.write([UInt8]("test".utf8)) })
     }
     
     server["/redirect"] = { r in
-        return .MovedPermanently("http://www.google.com")
+        return .movedPermanently("http://www.google.com")
     }
     
     server["/long"] = { r in
         var longResponse = ""
         for k in 0..<1000 { longResponse += "(\(k)),->" }
-        return .OK(.Html(longResponse))
+        return .ok(.html(longResponse))
     }
     
     server["/wildcard/*/test/*/:param"] = { r in
-        return .OK(.Html(r.path))
+        return .ok(.html(r.path))
     }
     
     server["/stream"] = { r in
-        return HttpResponse.RAW(200, "OK", nil, { w in
+        return HttpResponse.raw(200, "OK", nil, { w in
             for i in 0...100 {
                 w.write([UInt8]("[chunk \(i)]".utf8))
             }
@@ -186,7 +186,7 @@ public func demoServer(_ publicDir: String) -> HttpServer {
     })
     
     server.notFoundHandler = { r in
-        return .MovedPermanently("https://github.com/404")
+        return .movedPermanently("https://github.com/404")
     }
     
     server.middleware.append { r in

+ 19 - 27
Sources/Swifter/File.swift

@@ -12,13 +12,13 @@
 #endif
 
 public enum FileError: ErrorProtocol {
-    case OpenFailed(String)
-    case WriteFailed(String)
-    case ReadFailed(String)
-    case SeekFailed(String)
-    case GetCurrentWorkingDirectoryFailed(String)
-    case IsDirectoryFailed(String)
-    case OpenDirFailed(String)
+    case openFailed(String)
+    case writeFailed(String)
+    case readFailed(String)
+    case seekFailed(String)
+    case getCurrentWorkingDirectoryFailed(String)
+    case isDirectoryFailed(String)
+    case openDirFailed(String)
 }
 
 public class File {
@@ -37,7 +37,7 @@ public class File {
     
     public static func openFileForMode(_ path: String, _ mode: String) throws -> File {
         guard let file = path.withCString({ pathPointer in mode.withCString({ fopen(pathPointer, $0) }) }) else {
-            throw FileError.OpenFailed(descriptionOfLastError())
+            throw FileError.openFailed(descriptionOfLastError())
         }
         return File(file)
     }
@@ -45,26 +45,18 @@ public class File {
     public static func isDirectory(_ path: String) throws -> Bool {
         var s = stat()
         guard stat(path, &s) == 0 else {
-            throw FileError.IsDirectoryFailed(descriptionOfLastError())
+            throw FileError.isDirectoryFailed(descriptionOfLastError())
         }
         return s.st_mode & S_IFMT == S_IFDIR
     }
     
     public static func currentWorkingDirectory() throws -> String {
         guard let path = getcwd(nil, 0) else {
-            throw FileError.GetCurrentWorkingDirectoryFailed(descriptionOfLastError())
+            throw FileError.getCurrentWorkingDirectoryFailed(descriptionOfLastError())
         }
         return String(cString: path)
     }
     
-    public static func isDirectory(path: String) throws -> Bool {
-        var s = stat()
-        guard path.withCString({ stat($0, &s) }) == 0 else {
-            throw FileError.IsDirectoryFailed(descriptionOfLastError())
-        }
-        return s.st_mode & S_IFMT == S_IFDIR
-    }
-    
     public static func exists(_ path: String) throws -> Bool {
         var buffer = stat()
         return path.withCString({ stat($0, &buffer) == 0 })
@@ -73,7 +65,7 @@ public class File {
     public static func list(_ path: String) throws -> [String] {
         let dir = path.withCString { opendir($0) }
         if dir == nil {
-            throw FileError.OpenDirFailed(descriptionOfLastError())
+            throw FileError.openDirFailed(descriptionOfLastError())
         }
         defer { closedir(dir) }
         var results = [String]()
@@ -120,9 +112,9 @@ public class File {
             return count
         }
         if ferror(self.pointer) != 0 {
-            throw FileError.ReadFailed(File.descriptionOfLastError())
+            throw FileError.readFailed(File.descriptionOfLastError())
         }
-        throw FileError.ReadFailed("Unknown file read error occured.")
+        throw FileError.readFailed("Unknown file read error occured.")
     }
 
     public func write(_ data: [UInt8]) throws -> Void {
@@ -131,14 +123,14 @@ public class File {
         }
         try data.withUnsafeBufferPointer {
             if fwrite($0.baseAddress, 1, data.count, self.pointer) != data.count {
-                throw FileError.WriteFailed(File.descriptionOfLastError())
+                throw FileError.writeFailed(File.descriptionOfLastError())
             }
         }
     }
     
-    public func seek(offset: Int) throws -> Void {
+    public func seek(_ offset: Int) throws -> Void {
         if fseek(self.pointer, offset, SEEK_SET) != 0 {
-            throw FileError.SeekFailed(File.descriptionOfLastError())
+            throw FileError.seekFailed(File.descriptionOfLastError())
         }
     }
     
@@ -149,15 +141,15 @@ public class File {
 
 extension File {
     
-    public static func withNewFileOpenedForWriting<Result>(path: String, _ f: (File) throws -> Result) throws -> Result {
+    public static func withNewFileOpenedForWriting<Result>(_ path: String, _ f: (File) throws -> Result) throws -> Result {
         return try withFileOpenedForMode(path, mode: "wb", f)
     }
     
-    public static func withFileOpenedForReading<Result>(path: String, _ f: (File) throws -> Result) throws -> Result {
+    public static func withFileOpenedForReading<Result>(_ path: String, _ f: (File) throws -> Result) throws -> Result {
         return try withFileOpenedForMode(path, mode: "rb", f)
     }
     
-    public static func withFileOpenedForWritingAndReading<Result>(path: String, _ f: (File) throws -> Result) throws -> Result {
+    public static func withFileOpenedForWritingAndReading<Result>(_ path: String, _ f: (File) throws -> Result) throws -> Result {
         return try withFileOpenedForMode(path, mode: "r+b", f)
     }
     

+ 8 - 8
Sources/Swifter/Files.swift

@@ -10,13 +10,13 @@ import Foundation
 public func shareFilesFromDirectory(_ directoryPath: String) -> ((HttpRequest) -> HttpResponse) {
     return { r in
         guard let fileRelativePath = r.params.first else {
-            return .NotFound
+            return .notFound
         }
         let absolutePath = directoryPath + "/" + fileRelativePath.1
         guard let file = try? File.openForReading(absolutePath) else {
-            return .NotFound
+            return .notFound
         }
-        return .RAW(200, "OK", [:], { writer in
+        return .raw(200, "OK", [:], { writer in
             writer.write(file)
             file.close()
         })
@@ -26,12 +26,12 @@ public func shareFilesFromDirectory(_ directoryPath: String) -> ((HttpRequest) -
 public func directoryBrowser(_ dir: String) -> ((HttpRequest) -> HttpResponse) {
     return { r in
         guard let (_, value) = r.params.first else {
-            return HttpResponse.NotFound
+            return HttpResponse.notFound
         }
         let filePath = dir + "/" + value
         do {
             guard try File.exists(filePath) else {
-                return HttpResponse.NotFound
+                return HttpResponse.notFound
             }
             if try File.isDirectory(filePath) {
                 let files = try File.list(filePath)
@@ -53,15 +53,15 @@ public func directoryBrowser(_ dir: String) -> ((HttpRequest) -> HttpResponse) {
                 }(r)
             } else {
                 guard let file = try? File.openForReading(filePath) else {
-                    return .NotFound
+                    return .notFound
                 }
-                return .RAW(200, "OK", [:], { writer in
+                return .raw(200, "OK", [:], { writer in
                     writer.write(file)
                     file.close()
                 })
             }
         } catch {
-            return HttpResponse.InternalServerError
+            return HttpResponse.internalServerError
         }
     }
 }

+ 4 - 4
Sources/Swifter/HttpParser.swift

@@ -12,7 +12,7 @@
 #endif
 
 enum HttpParserError: ErrorProtocol {
-    case InvalidStatusLine(String)
+    case invalidStatusLine(String)
 }
 
 public class HttpParser {
@@ -23,7 +23,7 @@ public class HttpParser {
         let statusLine = try socket.readLine()
         let statusLineTokens = statusLine.split(" ")
         if statusLineTokens.count < 3 {
-            throw HttpParserError.InvalidStatusLine(statusLine)
+            throw HttpParserError.invalidStatusLine(statusLine)
         }
         let request = HttpRequest()
         request.method = statusLineTokens[0]
@@ -42,7 +42,7 @@ public class HttpParser {
         }
         return query.split("&").reduce([(String, String)]()) { (c, s) -> [(String, String)] in
             let tokens = s.split(1, separator: "=")
-            if let name = tokens.first, value = tokens.last {
+            if let name = tokens.first, let value = tokens.last {
                 return c + [(name.removePercentEncoding(), value.removePercentEncoding())]
             }
             return c
@@ -63,7 +63,7 @@ public class HttpParser {
                 return headers
             }
             let headerTokens = headerLine.split(1, separator: ":")
-            if let name = headerTokens.first, value = headerTokens.last {
+            if let name = headerTokens.first, let value = headerTokens.last {
                 headers[name.lowercased()] = value.trim()
             }
         } while true

+ 8 - 8
Sources/Swifter/HttpRequest.swift

@@ -29,12 +29,12 @@ public class HttpRequest {
             return []
         }
         let contentTypeHeaderTokens = contentTypeHeader.split(";").map { $0.trim() }
-        guard let contentType = contentTypeHeaderTokens.first where contentType == "application/x-www-form-urlencoded" else {
+        guard let contentType = contentTypeHeaderTokens.first, contentType == "application/x-www-form-urlencoded" else {
             return []
         }
         return String.fromUInt8(body).split("&").map { param -> (String, String) in
             let tokens = param.split("=")
-            if let name = tokens.first, value = tokens.last where tokens.count == 2 {
+            if let name = tokens.first, let value = tokens.last, tokens.count == 2 {
                 return (name.replace("+", " ").removePercentEncoding(),
                         value.replace("+", " ").removePercentEncoding())
             }
@@ -77,17 +77,17 @@ public class HttpRequest {
             return []
         }
         let contentTypeHeaderTokens = contentTypeHeader.split(";").map { $0.trim() }
-        guard let contentType = contentTypeHeaderTokens.first where contentType == "multipart/form-data" else {
+        guard let contentType = contentTypeHeaderTokens.first, contentType == "multipart/form-data" else {
             return []
         }
         var boundary: String? = nil
         contentTypeHeaderTokens.forEach({
             let tokens = $0.split("=")
-            if let key = tokens.first where key == "boundary" && tokens.count == 2 {
+            if let key = tokens.first, key == "boundary" && tokens.count == 2 {
                 boundary = tokens.last
             }
         })
-        if let boundary = boundary where boundary.utf8.count > 0 {
+        if let boundary = boundary, boundary.utf8.count > 0 {
             return parseMultiPartFormData(body, boundary: "--\(boundary)")
         }
         return []
@@ -111,9 +111,9 @@ public class HttpRequest {
             let /* ignore */ _ = nextMultiPartLine(&generator)
         }
         var headers = [String: String]()
-        while let line = nextMultiPartLine(&generator) where !line.isEmpty {
+        while let line = nextMultiPartLine(&generator), !line.isEmpty {
             let tokens = line.split(":")
-            if let name = tokens.first, value = tokens.last where tokens.count == 2 {
+            if let name = tokens.first, let value = tokens.last, tokens.count == 2 {
                 headers[name.lowercased()] = value.trim()
             }
         }
@@ -147,7 +147,7 @@ public class HttpRequest {
             matchOffset = ( x == boundaryArray[matchOffset] ? matchOffset + 1 : 0 )
             body.append(x)
             if matchOffset == boundaryArray.count {
-                body.removeSubrange(Range<Int>(body.count-matchOffset ..< body.count))
+                body.removeSubrange(CountableRange<Int>(body.count-matchOffset ..< body.count))
                 if body.last == HttpRequest.NL {
                     body.removeLast()
                     if body.last == HttpRequest.CR {

+ 53 - 53
Sources/Swifter/HttpResponse.swift

@@ -8,8 +8,8 @@
 import Foundation
 
 public enum SerializationError: ErrorProtocol {
-    case InvalidObject
-    case NotSupported
+    case invalidObject
+    case notSupported
 }
 
 public protocol HttpResponseBodyWriter {
@@ -20,16 +20,16 @@ public protocol HttpResponseBodyWriter {
 
 public enum HttpResponseBody {
     
-    case Json(AnyObject)
-    case Html(String)
-    case Text(String)
-    case Data([UInt8])
-    case Custom(Any, (Any) throws -> String)
+    case json(AnyObject)
+    case html(String)
+    case text(String)
+    case data([UInt8])
+    case custom(Any, (Any) throws -> String)
     
     func content() -> (Int, ((HttpResponseBodyWriter) throws -> Void)?) {
         do {
             switch self {
-            case .Json(let object):
+            case .json(let object):
                 #if os(Linux)
                     let data = [UInt8]("Not ready for Linux.".utf8)
                     return (data.count, {
@@ -37,7 +37,7 @@ public enum HttpResponseBody {
                     })
                 #else
                     guard JSONSerialization.isValidJSONObject(object) else {
-                        throw SerializationError.InvalidObject
+                        throw SerializationError.invalidObject
                     }
                     let json = try JSONSerialization.data(withJSONObject: object, options: JSONSerialization.WritingOptions.prettyPrinted)
                     let data = json.withUnsafeBytes({ (body: UnsafePointer<UInt8>) -> Array<UInt8> in
@@ -47,22 +47,22 @@ public enum HttpResponseBody {
                         $0.write(data)
                     })
                 #endif
-            case .Text(let body):
+            case .text(let body):
                 let data = [UInt8](body.utf8)
                 return (data.count, {
                     $0.write(data)
                 })
-            case .Html(let body):
+            case .html(let body):
                 let serialised = "<html><meta charset=\"UTF-8\"><body>\(body)</body></html>"
                 let data = [UInt8](serialised.utf8)
                 return (data.count, {
                     $0.write(data)
                 })
-            case .Data(let body):
+            case .data(let body):
                 return (body.count, {
                     $0.write(body)
                 })
-            case .Custom(let object, let closure):
+            case .custom(let object, let closure):
                 let serialised = try closure(object)
                 let data = [UInt8](serialised.utf8)
                 return (data.count, {
@@ -80,63 +80,63 @@ public enum HttpResponseBody {
 
 public enum HttpResponse {
     
-    case SwitchProtocols([String: String], (Socket) -> Void)
-    case OK(HttpResponseBody), Created, Accepted
-    case MovedPermanently(String)
-    case BadRequest(HttpResponseBody?), Unauthorized, Forbidden, NotFound
-    case InternalServerError
-    case RAW(Int, String, [String:String]?, ((HttpResponseBodyWriter) -> Void)? )
+    case switchProtocols([String: String], (Socket) -> Void)
+    case ok(HttpResponseBody), created, accepted
+    case movedPermanently(String)
+    case badRequest(HttpResponseBody?), unauthorized, forbidden, notFound
+    case internalServerError
+    case raw(Int, String, [String:String]?, ((HttpResponseBodyWriter) -> Void)? )
     
     func statusCode() -> Int {
         switch self {
-        case .SwitchProtocols(_, _)   : return 101
-        case .OK(_)                   : return 200
-        case .Created                 : return 201
-        case .Accepted                : return 202
-        case .MovedPermanently        : return 301
-        case .BadRequest(_)           : return 400
-        case .Unauthorized            : return 401
-        case .Forbidden               : return 403
-        case .NotFound                : return 404
-        case .InternalServerError     : return 500
-        case .RAW(let code, _ , _, _) : return code
+        case .switchProtocols(_, _)   : return 101
+        case .ok(_)                   : return 200
+        case .created                 : return 201
+        case .accepted                : return 202
+        case .movedPermanently        : return 301
+        case .badRequest(_)           : return 400
+        case .unauthorized            : return 401
+        case .forbidden               : return 403
+        case .notFound                : return 404
+        case .internalServerError     : return 500
+        case .raw(let code, _ , _, _) : return code
         }
     }
     
     func reasonPhrase() -> String {
         switch self {
-        case .SwitchProtocols(_, _)    : return "Switching Protocols"
-        case .OK(_)                    : return "OK"
-        case .Created                  : return "Created"
-        case .Accepted                 : return "Accepted"
-        case .MovedPermanently         : return "Moved Permanently"
-        case .BadRequest(_)            : return "Bad Request"
-        case .Unauthorized             : return "Unauthorized"
-        case .Forbidden                : return "Forbidden"
-        case .NotFound                 : return "Not Found"
-        case .InternalServerError      : return "Internal Server Error"
-        case .RAW(_, let phrase, _, _) : return phrase
+        case .switchProtocols(_, _)    : return "Switching Protocols"
+        case .ok(_)                    : return "OK"
+        case .created                  : return "Created"
+        case .accepted                 : return "Accepted"
+        case .movedPermanently         : return "Moved Permanently"
+        case .badRequest(_)            : return "Bad Request"
+        case .unauthorized             : return "Unauthorized"
+        case .forbidden                : return "Forbidden"
+        case .notFound                 : return "Not Found"
+        case .internalServerError      : return "Internal Server Error"
+        case .raw(_, let phrase, _, _) : return phrase
         }
     }
     
     func headers() -> [String: String] {
         var headers = ["Server" : "Swifter \(HttpServer.VERSION)"]
         switch self {
-        case .SwitchProtocols(let switchHeaders, _):
+        case .switchProtocols(let switchHeaders, _):
             for (key, value) in switchHeaders {
                 headers[key] = value
             }
-        case .OK(let body):
+        case .ok(let body):
             switch body {
-            case .Text(_)   : headers["Content-Type"] = "text/plain"
-            case .Json(_)   : headers["Content-Type"] = "application/json"
-            case .Html(_)   : headers["Content-Type"] = "text/html"
-            case .Data(_)   : headers["Content-Type"] = "application/octet-stream"
+            case .text(_)   : headers["Content-Type"] = "text/plain"
+            case .json(_)   : headers["Content-Type"] = "application/json"
+            case .html(_)   : headers["Content-Type"] = "text/html"
+            case .data(_)   : headers["Content-Type"] = "application/octet-stream"
             default:break
             }
-        case .MovedPermanently(let location):
+        case .movedPermanently(let location):
             headers["Location"] = location
-        case .RAW(_, _, let rawHeaders, _):
+        case .raw(_, _, let rawHeaders, _):
             if let rawHeaders = rawHeaders {
                 for (k, v) in rawHeaders {
                     headers.updateValue(v, forKey: k)
@@ -149,16 +149,16 @@ public enum HttpResponse {
     
     func content() -> (length: Int, write: ((HttpResponseBodyWriter) throws -> Void)?) {
         switch self {
-        case .OK(let body)             : return body.content()
-        case .BadRequest(let body)     : return body?.content() ?? (-1, nil)
-        case .RAW(_, _, _, let writer) : return (-1, writer)
+        case .ok(let body)             : return body.content()
+        case .badRequest(let body)     : return body?.content() ?? (-1, nil)
+        case .raw(_, _, _, let writer) : return (-1, writer)
         default                        : return (-1, nil)
         }
     }
     
     func socketSession() -> ((Socket) -> Void)?  {
         switch self {
-        case SwitchProtocols(_, let handler) : return handler
+        case switchProtocols(_, let handler) : return handler
         default: return nil
         }
     }

+ 1 - 1
Sources/Swifter/HttpServerIO.swift

@@ -49,7 +49,7 @@ public class HttpServerIO {
     }
     
     public func dispatch(_ request: HttpRequest) -> ([String: String], (HttpRequest) -> HttpResponse) {
-        return ([:], { _ in HttpResponse.NotFound })
+        return ([:], { _ in HttpResponse.notFound })
     }
     
     private func handleConnection(_ socket: Socket) {

+ 4 - 4
Sources/Swifter/Reflection.swift

@@ -65,7 +65,7 @@ public extension DatabaseReflectionProtocol {
         return (instance, name, fields)
     }
     
-    static func find(id: UInt64) -> Self? {
+    static func find(_ id: UInt64) -> Self? {
         let (instance, _, _) = classInstanceWithSchemeMethod2()
         // TODO - make a query to DB
         return instance
@@ -73,7 +73,7 @@ public extension DatabaseReflectionProtocol {
     
     public func insert() throws {
         guard let database = DatabaseReflection.sharedDatabase else {
-            throw SQLiteError.OpenFailed("Database connection is not opened.")
+            throw SQLiteError.openFailed("Database connection is not opened.")
         }
         let (name, fields) = schemeWithValuesAsString()
         try database.exec("CREATE TABLE IF NOT EXISTS \(name) (" + fields.map { "\($0.0) TEXT" }.joined(separator: ", ")  + ");")
@@ -84,8 +84,8 @@ public extension DatabaseReflectionProtocol {
     
 }
 
-public func memoryLayoutForStructure(object: Any) -> [String: Range<Int>] {
-    var layout = [String: Range<Int>]()
+public func memoryLayoutForStructure(_ object: Any) -> [String: CountableRange<Int>] {
+    var layout = [String: CountableRange<Int>]()
     var size = 0
     var alignment = 1
     for case let (label?, value) in Mirror(reflecting: object).children {

+ 12 - 12
Sources/Swifter/SQLite.swift

@@ -9,9 +9,9 @@ import Foundation
 import CSQLite
 
 public enum SQLiteError: ErrorProtocol {
-    case OpenFailed(String?)
-    case ExecFailed(String?)
-    case BindFailed(String?)
+    case openFailed(String?)
+    case execFailed(String?)
+    case bindFailed(String?)
 }
 
 public class SQLite {
@@ -22,10 +22,10 @@ public class SQLite {
         var databaseConnectionPointer: OpaquePointer? = nil
         let openResult = path.withCString { sqlite3_open($0, &databaseConnectionPointer) }
         guard let databaseConnection = databaseConnectionPointer else {
-            throw SQLiteError.ExecFailed("Invalid pointer.")
+            throw SQLiteError.execFailed("Invalid pointer.")
         }
         guard openResult == SQLITE_OK else {
-            throw SQLiteError.OpenFailed(String(cString: sqlite3_errmsg(databaseConnection)))
+            throw SQLiteError.openFailed(String(cString: sqlite3_errmsg(databaseConnection)))
         }
         return SQLite(databaseConnection)
     }
@@ -42,16 +42,16 @@ public class SQLite {
         var statementPointer: OpaquePointer? = nil
         let prepareResult = sql.withCString { sqlite3_prepare_v2(databaseConnection, $0, Int32(sql.utf8.count), &statementPointer, nil) }
         guard prepareResult == SQLITE_OK else {
-            throw SQLiteError.ExecFailed(String(cString: sqlite3_errmsg(databaseConnection)))
+            throw SQLiteError.execFailed(String(cString: sqlite3_errmsg(databaseConnection)))
         }
         guard let statement = statementPointer else {
-            throw SQLiteError.ExecFailed("Invalid pointer.")
+            throw SQLiteError.execFailed("Invalid pointer.")
         }
         for (index, value) in (params ?? [String?]()).enumerated() {
             let bindResult = value?.withCString({ sqlite3_bind_text(statement, index + 1, $0, -1 /* take zero terminator. */) { _ in } })
                     ?? sqlite3_bind_null(statement, index + 1)
             guard bindResult == SQLITE_OK else {
-                throw SQLiteError.BindFailed(String(cString: sqlite3_errmsg(databaseConnection)))
+                throw SQLiteError.bindFailed(String(cString: sqlite3_errmsg(databaseConnection)))
             }
         }
         while true {
@@ -71,9 +71,9 @@ public class SQLite {
             case SQLITE_DONE:
                 return
             case SQLITE_ERROR:
-                throw SQLiteError.ExecFailed("sqlite3_step() returned SQLITE_ERROR.")
+                throw SQLiteError.execFailed("sqlite3_step() returned SQLITE_ERROR.")
             default:
-                throw SQLiteError.ExecFailed("Unknown result for sqlite3_step(): \(stepResult)")
+                throw SQLiteError.execFailed("Unknown result for sqlite3_step(): \(stepResult)")
             }
         }
     }
@@ -83,10 +83,10 @@ public class SQLite {
         var statement: OpaquePointer? = nil
         let prepareResult = sql.withCString { sqlite3_prepare_v2(databaseConnection, $0, Int32(sql.utf8.count), &statement, nil) }
         guard prepareResult == SQLITE_OK else {
-            throw SQLiteError.ExecFailed(String(cString: sqlite3_errmsg(databaseConnection)))
+            throw SQLiteError.execFailed(String(cString: sqlite3_errmsg(databaseConnection)))
         }
         guard let readyStatement = statement else {
-            throw SQLiteError.ExecFailed("Invalid pointer.")
+            throw SQLiteError.execFailed("Invalid pointer.")
         }
         return StatmentSequence(statement: readyStatement)
     }

+ 146 - 146
Sources/Swifter/Scopes.swift

@@ -11,11 +11,11 @@
     import Foundation
 #endif
 
-public func scopes(scope: Closure) -> ((HttpRequest) -> HttpResponse) {
+public func scopes(_ scope: Closure) -> ((HttpRequest) -> HttpResponse) {
     return { r in
         ScopesBuffer[Process.TID] = ""
         scope()
-        return .RAW(200, "OK", ["Content-Type": "text/html"],
+        return .raw(200, "OK", ["Content-Type": "text/html"],
                     { $0.write([UInt8](("<!DOCTYPE html>"  + (ScopesBuffer[Process.TID] ?? "")).utf8)) })
     }
 }
@@ -147,29 +147,29 @@ public var acceptCharset: String? = nil
 
 public var inner: String? = nil
 
-public func a(c: Closure) { element("a", c) }
-public func b(c: Closure) { element("b", c) }
-public func i(c: Closure) { element("i", c) }
-public func p(c: Closure) { element("p", c) }
-public func q(c: Closure) { element("q", c) }
-public func s(c: Closure) { element("s", c) }
-public func u(c: Closure) { element("u", c) }
+public func a(_ c: Closure) { element("a", c) }
+public func b(_ c: Closure) { element("b", c) }
+public func i(_ c: Closure) { element("i", c) }
+public func p(_ c: Closure) { element("p", c) }
+public func q(_ c: Closure) { element("q", c) }
+public func s(_ c: Closure) { element("s", c) }
+public func u(_ c: Closure) { element("u", c) }
 
-public func br(c: Closure) { element("br", c) }
-public func dd(c: Closure) { element("dd", c) }
-public func dl(c: Closure) { element("dl", c) }
-public func dt(c: Closure) { element("dt", c) }
-public func em(c: Closure) { element("em", c) }
-public func hr(c: Closure) { element("hr", c) }
-public func li(c: Closure) { element("li", c) }
-public func ol(c: Closure) { element("ol", c) }
-public func rp(c: Closure) { element("rp", c) }
-public func rt(c: Closure) { element("rt", c) }
-public func td(c: Closure) { element("td", c) }
-public func th(c: Closure) { element("th", c) }
-public func tr(c: Closure) { element("tr", c) }
-public func tt(c: Closure) { element("tt", c) }
-public func ul(c: Closure) { element("ul", c) }
+public func br(_ c: Closure) { element("br", c) }
+public func dd(_ c: Closure) { element("dd", c) }
+public func dl(_ c: Closure) { element("dl", c) }
+public func dt(_ c: Closure) { element("dt", c) }
+public func em(_ c: Closure) { element("em", c) }
+public func hr(_ c: Closure) { element("hr", c) }
+public func li(_ c: Closure) { element("li", c) }
+public func ol(_ c: Closure) { element("ol", c) }
+public func rp(_ c: Closure) { element("rp", c) }
+public func rt(_ c: Closure) { element("rt", c) }
+public func td(_ c: Closure) { element("td", c) }
+public func th(_ c: Closure) { element("th", c) }
+public func tr(_ c: Closure) { element("tr", c) }
+public func tt(_ c: Closure) { element("tt", c) }
+public func ul(_ c: Closure) { element("ul", c) }
 
 public func ul<T: Sequence>(_ collection: T, _ c: (T.Iterator.Element) -> Void) {
     element("ul", {
@@ -179,70 +179,70 @@ public func ul<T: Sequence>(_ collection: T, _ c: (T.Iterator.Element) -> Void)
     })
 }
 
-public func h1(c: Closure) { element("h1", c) }
-public func h2(c: Closure) { element("h2", c) }
-public func h3(c: Closure) { element("h3", c) }
-public func h4(c: Closure) { element("h4", c) }
-public func h5(c: Closure) { element("h5", c) }
-public func h6(c: Closure) { element("h6", c) }
+public func h1(_ c: Closure) { element("h1", c) }
+public func h2(_ c: Closure) { element("h2", c) }
+public func h3(_ c: Closure) { element("h3", c) }
+public func h4(_ c: Closure) { element("h4", c) }
+public func h5(_ c: Closure) { element("h5", c) }
+public func h6(_ c: Closure) { element("h6", c) }
 
-public func bdi(c: Closure) { element("bdi", c) }
-public func bdo(c: Closure) { element("bdo", c) }
-public func big(c: Closure) { element("big", c) }
-public func col(c: Closure) { element("col", c) }
-public func del(c: Closure) { element("del", c) }
-public func dfn(c: Closure) { element("dfn", c) }
-public func dir(c: Closure) { element("dir", c) }
-public func div(c: Closure) { element("div", c) }
-public func img(c: Closure) { element("img", c) }
-public func ins(c: Closure) { element("ins", c) }
-public func kbd(c: Closure) { element("kbd", c) }
-public func map(c: Closure) { element("map", c) }
-public func nav(c: Closure) { element("nav", c) }
-public func pre(c: Closure) { element("pre", c) }
-public func rtc(c: Closure) { element("rtc", c) }
-public func sub(c: Closure) { element("sub", c) }
-public func sup(c: Closure) { element("sup", c) }
+public func bdi(_ c: Closure) { element("bdi", c) }
+public func bdo(_ c: Closure) { element("bdo", c) }
+public func big(_ c: Closure) { element("big", c) }
+public func col(_ c: Closure) { element("col", c) }
+public func del(_ c: Closure) { element("del", c) }
+public func dfn(_ c: Closure) { element("dfn", c) }
+public func dir(_ c: Closure) { element("dir", c) }
+public func div(_ c: Closure) { element("div", c) }
+public func img(_ c: Closure) { element("img", c) }
+public func ins(_ c: Closure) { element("ins", c) }
+public func kbd(_ c: Closure) { element("kbd", c) }
+public func map(_ c: Closure) { element("map", c) }
+public func nav(_ c: Closure) { element("nav", c) }
+public func pre(_ c: Closure) { element("pre", c) }
+public func rtc(_ c: Closure) { element("rtc", c) }
+public func sub(_ c: Closure) { element("sub", c) }
+public func sup(_ c: Closure) { element("sup", c) }
 
-public func varr(c: Closure) { element("var", c) }
-public func wbr(c: Closure) { element("wbr", c) }
-public func xmp(c: Closure) { element("xmp", c) }
+public func varr(_ c: Closure) { element("var", c) }
+public func wbr(_ c: Closure) { element("wbr", c) }
+public func xmp(_ c: Closure) { element("xmp", c) }
 
-public func abbr(c: Closure) { element("abbr", c) }
-public func area(c: Closure) { element("area", c) }
-public func base(c: Closure) { element("base", c) }
-public func body(c: Closure) { element("body", c) }
-public func cite(c: Closure) { element("cite", c) }
-public func code(c: Closure) { element("code", c) }
-public func data(c: Closure) { element("data", c) }
-public func font(c: Closure) { element("font", c) }
-public func form(c: Closure) { element("form", c) }
-public func head(c: Closure) { element("head", c) }
-public func html(c: Closure) { element("html", c) }
-public func link(c: Closure) { element("link", c) }
-public func main(c: Closure) { element("main", c) }
-public func mark(c: Closure) { element("mark", c) }
-public func menu(c: Closure) { element("menu", c) }
-public func meta(c: Closure) { element("meta", c) }
-public func nobr(c: Closure) { element("nobr", c) }
-public func ruby(c: Closure) { element("ruby", c) }
-public func samp(c: Closure) { element("samp", c) }
-public func span(c: Closure) { element("span", c) }
-public func time(c: Closure) { element("time", c) }
+public func abbr(_ c: Closure) { element("abbr", c) }
+public func area(_ c: Closure) { element("area", c) }
+public func base(_ c: Closure) { element("base", c) }
+public func body(_ c: Closure) { element("body", c) }
+public func cite(_ c: Closure) { element("cite", c) }
+public func code(_ c: Closure) { element("code", c) }
+public func data(_ c: Closure) { element("data", c) }
+public func font(_ c: Closure) { element("font", c) }
+public func form(_ c: Closure) { element("form", c) }
+public func head(_ c: Closure) { element("head", c) }
+public func html(_ c: Closure) { element("html", c) }
+public func link(_ c: Closure) { element("link", c) }
+public func main(_ c: Closure) { element("main", c) }
+public func mark(_ c: Closure) { element("mark", c) }
+public func menu(_ c: Closure) { element("menu", c) }
+public func meta(_ c: Closure) { element("meta", c) }
+public func nobr(_ c: Closure) { element("nobr", c) }
+public func ruby(_ c: Closure) { element("ruby", c) }
+public func samp(_ c: Closure) { element("samp", c) }
+public func span(_ c: Closure) { element("span", c) }
+public func time(_ c: Closure) { element("time", c) }
 
-public func aside(c: Closure) { element("aside", c) }
-public func audio(c: Closure) { element("audio", c) }
-public func blink(c: Closure) { element("blink", c) }
-public func embed(c: Closure) { element("embed", c) }
-public func frame(c: Closure) { element("frame", c) }
-public func image(c: Closure) { element("image", c) }
-public func input(c: Closure) { element("input", c) }
-public func label(c: Closure) { element("label", c) }
-public func meter(c: Closure) { element("meter", c) }
-public func param(c: Closure) { element("param", c) }
-public func small(c: Closure) { element("small", c) }
-public func style(c: Closure) { element("style", c) }
-public func table(c: Closure) { element("table", c) }
+public func aside(_ c: Closure) { element("aside", c) }
+public func audio(_ c: Closure) { element("audio", c) }
+public func blink(_ c: Closure) { element("blink", c) }
+public func embed(_ c: Closure) { element("embed", c) }
+public func frame(_ c: Closure) { element("frame", c) }
+public func image(_ c: Closure) { element("image", c) }
+public func input(_ c: Closure) { element("input", c) }
+public func label(_ c: Closure) { element("label", c) }
+public func meter(_ c: Closure) { element("meter", c) }
+public func param(_ c: Closure) { element("param", c) }
+public func small(_ c: Closure) { element("small", c) }
+public func style(_ c: Closure) { element("style", c) }
+public func table(_ c: Closure) { element("table", c) }
 
 public func table<T: Sequence>(_ collection: T, c: (T.Iterator.Element) -> Void) {
     element("table", {
@@ -252,7 +252,7 @@ public func table<T: Sequence>(_ collection: T, c: (T.Iterator.Element) -> Void)
     })
 }
 
-public func tbody(c: Closure) { element("tbody", c) }
+public func tbody(_ c: Closure) { element("tbody", c) }
 
 public func tbody<T: Sequence>(_ collection: T, c: (T.Iterator.Element) -> Void) {
     element("tbody", {
@@ -262,72 +262,72 @@ public func tbody<T: Sequence>(_ collection: T, c: (T.Iterator.Element) -> Void)
     })
 }
 
-public func tfoot(c: Closure) { element("tfoot", c) }
-public func thead(c: Closure) { element("thead", c) }
-public func title(c: Closure) { element("title", c) }
-public func track(c: Closure) { element("track", c) }
-public func video(c: Closure) { element("video", c) }
+public func tfoot(_ c: Closure) { element("tfoot", c) }
+public func thead(_ c: Closure) { element("thead", c) }
+public func title(_ c: Closure) { element("title", c) }
+public func track(_ c: Closure) { element("track", c) }
+public func video(_ c: Closure) { element("video", c) }
 
-public func applet(c: Closure) { element("applet", c) }
-public func button(c: Closure) { element("button", c) }
-public func canvas(c: Closure) { element("canvas", c) }
-public func center(c: Closure) { element("center", c) }
-public func dialog(c: Closure) { element("dialog", c) }
-public func figure(c: Closure) { element("figure", c) }
-public func footer(c: Closure) { element("footer", c) }
-public func header(c: Closure) { element("header", c) }
-public func hgroup(c: Closure) { element("hgroup", c) }
-public func iframe(c: Closure) { element("iframe", c) }
-public func keygen(c: Closure) { element("keygen", c) }
-public func legend(c: Closure) { element("legend", c) }
-public func object(c: Closure) { element("object", c) }
-public func option(c: Closure) { element("option", c) }
-public func output(c: Closure) { element("output", c) }
-public func script(c: Closure) { element("script", c) }
-public func select(c: Closure) { element("select", c) }
-public func shadow(c: Closure) { element("shadow", c) }
-public func source(c: Closure) { element("source", c) }
-public func spacer(c: Closure) { element("spacer", c) }
-public func strike(c: Closure) { element("strike", c) }
-public func strong(c: Closure) { element("strong", c) }
+public func applet(_ c: Closure) { element("applet", c) }
+public func button(_ c: Closure) { element("button", c) }
+public func canvas(_ c: Closure) { element("canvas", c) }
+public func center(_ c: Closure) { element("center", c) }
+public func dialog(_ c: Closure) { element("dialog", c) }
+public func figure(_ c: Closure) { element("figure", c) }
+public func footer(_ c: Closure) { element("footer", c) }
+public func header(_ c: Closure) { element("header", c) }
+public func hgroup(_ c: Closure) { element("hgroup", c) }
+public func iframe(_ c: Closure) { element("iframe", c) }
+public func keygen(_ c: Closure) { element("keygen", c) }
+public func legend(_ c: Closure) { element("legend", c) }
+public func object(_ c: Closure) { element("object", c) }
+public func option(_ c: Closure) { element("option", c) }
+public func output(_ c: Closure) { element("output", c) }
+public func script(_ c: Closure) { element("script", c) }
+public func select(_ c: Closure) { element("select", c) }
+public func shadow(_ c: Closure) { element("shadow", c) }
+public func source(_ c: Closure) { element("source", c) }
+public func spacer(_ c: Closure) { element("spacer", c) }
+public func strike(_ c: Closure) { element("strike", c) }
+public func strong(_ c: Closure) { element("strong", c) }
 
-public func acronym(c: Closure) { element("acronym", c) }
-public func address(c: Closure) { element("address", c) }
-public func article(c: Closure) { element("article", c) }
-public func bgsound(c: Closure) { element("bgsound", c) }
-public func caption(c: Closure) { element("caption", c) }
-public func command(c: Closure) { element("command", c) }
-public func content(c: Closure) { element("content", c) }
-public func details(c: Closure) { element("details", c) }
-public func elementt(c: Closure) { element("element", c) }
-public func isindex(c: Closure) { element("isindex", c) }
-public func listing(c: Closure) { element("listing", c) }
-public func marquee(c: Closure) { element("marquee", c) }
-public func noembed(c: Closure) { element("noembed", c) }
-public func picture(c: Closure) { element("picture", c) }
-public func section(c: Closure) { element("section", c) }
-public func summary(c: Closure) { element("summary", c) }
+public func acronym(_ c: Closure) { element("acronym", c) }
+public func address(_ c: Closure) { element("address", c) }
+public func article(_ c: Closure) { element("article", c) }
+public func bgsound(_ c: Closure) { element("bgsound", c) }
+public func caption(_ c: Closure) { element("caption", c) }
+public func command(_ c: Closure) { element("command", c) }
+public func content(_ c: Closure) { element("content", c) }
+public func details(_ c: Closure) { element("details", c) }
+public func elementt(_ c: Closure) { element("element", c) }
+public func isindex(_ c: Closure) { element("isindex", c) }
+public func listing(_ c: Closure) { element("listing", c) }
+public func marquee(_ c: Closure) { element("marquee", c) }
+public func noembed(_ c: Closure) { element("noembed", c) }
+public func picture(_ c: Closure) { element("picture", c) }
+public func section(_ c: Closure) { element("section", c) }
+public func summary(_ c: Closure) { element("summary", c) }
 
-public func basefont(c: Closure) { element("basefont", c) }
-public func colgroup(c: Closure) { element("colgroup", c) }
-public func datalist(c: Closure) { element("datalist", c) }
-public func fieldset(c: Closure) { element("fieldset", c) }
-public func frameset(c: Closure) { element("frameset", c) }
-public func menuitem(c: Closure) { element("menuitem", c) }
-public func multicol(c: Closure) { element("multicol", c) }
-public func noframes(c: Closure) { element("noframes", c) }
-public func noscript(c: Closure) { element("noscript", c) }
-public func optgroup(c: Closure) { element("optgroup", c) }
-public func progress(c: Closure) { element("progress", c) }
-public func template(c: Closure) { element("template", c) }
-public func textarea(c: Closure) { element("textarea", c) }
+public func basefont(_ c: Closure) { element("basefont", c) }
+public func colgroup(_ c: Closure) { element("colgroup", c) }
+public func datalist(_ c: Closure) { element("datalist", c) }
+public func fieldset(_ c: Closure) { element("fieldset", c) }
+public func frameset(_ c: Closure) { element("frameset", c) }
+public func menuitem(_ c: Closure) { element("menuitem", c) }
+public func multicol(_ c: Closure) { element("multicol", c) }
+public func noframes(_ c: Closure) { element("noframes", c) }
+public func noscript(_ c: Closure) { element("noscript", c) }
+public func optgroup(_ c: Closure) { element("optgroup", c) }
+public func progress(_ c: Closure) { element("progress", c) }
+public func template(_ c: Closure) { element("template", c) }
+public func textarea(_ c: Closure) { element("textarea", c) }
 
-public func plaintext(c: Closure) { element("plaintext", c) }
-public func javascript(c: Closure) { element("script", ["type": "text/javascript"], c) }
-public func blockquote(c: Closure) { element("blockquote", c) }
-public func figcaption(c: Closure) { element("figcaption", c) }
+public func plaintext(_ c: Closure) { element("plaintext", c) }
+public func javascript(_ c: Closure) { element("script", ["type": "text/javascript"], c) }
+public func blockquote(_ c: Closure) { element("blockquote", c) }
+public func figcaption(_ c: Closure) { element("figcaption", c) }
 
-public func stylesheet(c: Closure) { element("link", ["rel": "stylesheet", "type": "text/css"], c) }
+public func stylesheet(_ c: Closure) { element("link", ["rel": "stylesheet", "type": "text/css"], c) }
 
 public func element(_ node: String, _ c: Closure) { evaluate(node, [:], c) }
 public func element(_ node: String, _ attrs: [String: String?] = [:], _ c: Closure) { evaluate(node, attrs, c) }

+ 20 - 20
Sources/Swifter/Socket.swift

@@ -14,16 +14,16 @@
 /* Low level routines for POSIX sockets */
 
 public enum SocketError: ErrorProtocol {
-    case SocketCreationFailed(String)
-    case SocketSettingReUseAddrFailed(String)
-    case BindFailed(String)
-    case ListenFailed(String)
-    case WriteFailed(String)
-    case GetPeerNameFailed(String)
-    case ConvertingPeerNameFailed
-    case GetNameInfoFailed(String)
-    case AcceptFailed(String)
-    case RecvFailed(String)
+    case socketCreationFailed(String)
+    case socketSettingReUseAddrFailed(String)
+    case bindFailed(String)
+    case listenFailed(String)
+    case writeFailed(String)
+    case getPeerNameFailed(String)
+    case convertingPeerNameFailed
+    case getNameInfoFailed(String)
+    case acceptFailed(String)
+    case recvFailed(String)
 }
 
 public class Socket: Hashable, Equatable {
@@ -37,14 +37,14 @@ public class Socket: Hashable, Equatable {
         #endif
         
         if socketFileDescriptor == -1 {
-            throw SocketError.SocketCreationFailed(Socket.descriptionOfLastError())
+            throw SocketError.socketCreationFailed(Socket.descriptionOfLastError())
         }
         
         var value: Int32 = 1
         if setsockopt(socketFileDescriptor, SOL_SOCKET, SO_REUSEADDR, &value, socklen_t(sizeof(Int32.self))) == -1 {
             let details = Socket.descriptionOfLastError()
             Socket.release(socketFileDescriptor)
-            throw SocketError.SocketSettingReUseAddrFailed(details)
+            throw SocketError.socketSettingReUseAddrFailed(details)
         }
         Socket.setNoSigPipe(socketFileDescriptor)
         
@@ -93,13 +93,13 @@ public class Socket: Hashable, Equatable {
         if bindResult == -1 {
             let details = Socket.descriptionOfLastError()
             Socket.release(socketFileDescriptor)
-            throw SocketError.BindFailed(details)
+            throw SocketError.bindFailed(details)
         }
         
         if listen(socketFileDescriptor, maxPendingConnection ) == -1 {
             let details = Socket.descriptionOfLastError()
             Socket.release(socketFileDescriptor)
-            throw SocketError.ListenFailed(details)
+            throw SocketError.listenFailed(details)
         }
         return Socket(socketFileDescriptor: socketFileDescriptor)
     }
@@ -125,7 +125,7 @@ public class Socket: Hashable, Equatable {
         var len: socklen_t = 0
         let clientSocket = accept(self.socketFileDescriptor, &addr, &len)
         if clientSocket == -1 {
-            throw SocketError.AcceptFailed(Socket.descriptionOfLastError())
+            throw SocketError.acceptFailed(Socket.descriptionOfLastError())
         }
         Socket.setNoSigPipe(clientSocket)
         return Socket(socketFileDescriptor: clientSocket)
@@ -142,7 +142,7 @@ public class Socket: Hashable, Equatable {
     public func writeUInt8(_ data: ArraySlice<UInt8>) throws {
         try data.withUnsafeBufferPointer {
             guard let baseAddress = $0.baseAddress else {
-                throw SocketError.WriteFailed("The base address of data slice is nil.")
+                throw SocketError.writeFailed("The base address of data slice is nil.")
             }
             var sent = 0
             while sent < data.count {
@@ -152,7 +152,7 @@ public class Socket: Hashable, Equatable {
                     let s = write(self.socketFileDescriptor, baseAddress + sent, Int(data.count - sent))
                 #endif
                 if s <= 0 {
-                    throw SocketError.WriteFailed(Socket.descriptionOfLastError())
+                    throw SocketError.writeFailed(Socket.descriptionOfLastError())
                 }
                 sent += s
             }
@@ -163,7 +163,7 @@ public class Socket: Hashable, Equatable {
         var buffer = [UInt8](repeating: 0, count: 1)
         let next = recv(self.socketFileDescriptor as Int32, &buffer, Int(buffer.count), 0)
         if next <= 0 {
-            throw SocketError.RecvFailed(Socket.descriptionOfLastError())
+            throw SocketError.recvFailed(Socket.descriptionOfLastError())
         }
         return buffer[0]
     }
@@ -184,11 +184,11 @@ public class Socket: Hashable, Equatable {
     public func peername() throws -> String {
         var addr = sockaddr(), len: socklen_t = socklen_t(sizeof(sockaddr.self))
         if getpeername(self.socketFileDescriptor, &addr, &len) != 0 {
-            throw SocketError.GetPeerNameFailed(Socket.descriptionOfLastError())
+            throw SocketError.getPeerNameFailed(Socket.descriptionOfLastError())
         }
         var hostBuffer = [CChar](repeating: 0, count: Int(NI_MAXHOST))
         if getnameinfo(&addr, len, &hostBuffer, socklen_t(hostBuffer.count), nil, 0, NI_NUMERICHOST) != 0 {
-            throw SocketError.GetNameInfoFailed(Socket.descriptionOfLastError())
+            throw SocketError.getNameInfoFailed(Socket.descriptionOfLastError())
         }
         return String(cString: hostBuffer)
     }

+ 1 - 1
Sources/Swifter/String+Misc.swift

@@ -57,7 +57,7 @@ extension String {
             if scalar == "%" {
                 let first = scalars.popFirst()
                 let secon = scalars.popFirst()
-                if let first = first?.asAlpha(), secon = secon?.asAlpha() {
+                if let first = first?.asAlpha(), let secon = secon?.asAlpha() {
                     decodeBuffer.append(first*16+secon)
                 } else {
                     if !decodeBuffer.isEmpty {

+ 13 - 13
Sources/Swifter/WebSockets.swift

@@ -13,23 +13,23 @@ public func websocket(
     _ binary: ((WebSocketSession, [UInt8]) -> Void)?) -> ((HttpRequest) -> HttpResponse) {
     return { r in
         guard r.hasTokenForHeader("upgrade", token: "websocket") else {
-            return .BadRequest(.Text("Invalid value of 'Upgrade' header: \(r.headers["upgrade"])"))
+            return .badRequest(.text("Invalid value of 'Upgrade' header: \(r.headers["upgrade"])"))
         }
         guard r.hasTokenForHeader("connection", token: "upgrade") else {
-            return .BadRequest(.Text("Invalid value of 'Connection' header: \(r.headers["connection"])"))
+            return .badRequest(.text("Invalid value of 'Connection' header: \(r.headers["connection"])"))
         }
         guard let secWebSocketKey = r.headers["sec-websocket-key"] else {
-            return .BadRequest(.Text("Invalid value of 'Sec-Websocket-Key' header: \(r.headers["sec-websocket-key"])"))
+            return .badRequest(.text("Invalid value of 'Sec-Websocket-Key' header: \(r.headers["sec-websocket-key"])"))
         }
         let protocolSessionClosure: ((Socket) -> Void) = { socket in
             let session = WebSocketSession(socket)
             while let frame = try? session.readFrame() {
                 switch frame.opcode {
-                case .Text:
+                case .text:
                     if let handleText = text {
                         handleText(session, String.fromUInt8(frame.payload))
                     }
-                case .Binary:
+                case .binary:
                     if let handleBinary = binary {
                         handleBinary(session, frame.payload)
                     }
@@ -39,17 +39,17 @@ public func websocket(
         }
         let secWebSocketAccept = String.toBase64((secWebSocketKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").SHA1())
         let headers = [ "Upgrade": "WebSocket", "Connection": "Upgrade", "Sec-WebSocket-Accept": secWebSocketAccept]
-        return HttpResponse.SwitchProtocols(headers, protocolSessionClosure)
+        return HttpResponse.switchProtocols(headers, protocolSessionClosure)
     }
 }
 
 public class WebSocketSession {
     
-    public enum Error: ErrorProtocol { case UnknownOpCode(String), UnMaskedFrame }
-    public enum OpCode: UInt8 { case Continue = 0x00, Close = 0x08, Ping = 0x09, Pong = 0x0A, Text = 0x01, Binary = 0x02 }
+    public enum Error: ErrorProtocol { case unknownOpCode(String), unMaskedFrame }
+    public enum OpCode: UInt8 { case `continue` = 0x00, close = 0x08, ping = 0x09, pong = 0x0A, text = 0x01, binary = 0x02 }
     
     public class Frame {
-        public var opcode = OpCode.Close
+        public var opcode = OpCode.close
         public var fin = false
         public var payload = [UInt8]()
     }
@@ -61,7 +61,7 @@ public class WebSocketSession {
     }
     
     public func writeText(_ text: String) -> Void {
-        self.writeFrame(ArraySlice(text.utf8), OpCode.Text)
+        self.writeFrame(ArraySlice(text.utf8), OpCode.text)
     }
 
     public func writeBinary(_ binary: [UInt8]) -> Void {
@@ -69,7 +69,7 @@ public class WebSocketSession {
     }
     
     public func writeBinary(_ binary: ArraySlice<UInt8>) -> Void {
-        self.writeFrame(binary, OpCode.Binary)
+        self.writeFrame(binary, OpCode.binary)
     }
     
     private func writeFrame(_ data: ArraySlice<UInt8>, _ op: OpCode, _ fin: Bool = true) {
@@ -116,7 +116,7 @@ public class WebSocketSession {
         guard let opcode = OpCode(rawValue: opc) else {
             // "If an unknown opcode is received, the receiving endpoint MUST _Fail the WebSocket Connection_."
             // http://tools.ietf.org/html/rfc6455#section-5.2 ( Page 29 )
-            throw Error.UnknownOpCode("\(opc)")
+            throw Error.unknownOpCode("\(opc)")
         }
         frm.opcode = opcode
         let sec = try socket.read()
@@ -124,7 +124,7 @@ public class WebSocketSession {
         guard msk else {
             // "...a client MUST mask all frames that it sends to the serve.."
             // http://tools.ietf.org/html/rfc6455#section-5.1
-            throw Error.UnMaskedFrame
+            throw Error.unMaskedFrame
         }
         var len = UInt64(sec & 0x7F)
         if len == 0x7E {

+ 10 - 1
XCode/Swifter.xcodeproj/project.pbxproj

@@ -671,6 +671,7 @@
 					};
 					7AE893FA1C0512C400A29F63 = {
 						CreatedOnToolsVersion = 7.1;
+						LastSwiftMigration = 0800;
 						ProvisioningStyle = Manual;
 					};
 					7C839B6D19422CFF003A6950 = {
@@ -678,6 +679,7 @@
 					};
 					7CA4813A19A2EA8D0030B30D = {
 						CreatedOnToolsVersion = 6.0;
+						LastSwiftMigration = 0800;
 					};
 					7CCD1B641C8F7CEC0016D664 = {
 						CreatedOnToolsVersion = 7.2.1;
@@ -687,6 +689,7 @@
 					};
 					7CCD87781C660EA30068099B = {
 						CreatedOnToolsVersion = 7.2;
+						LastSwiftMigration = 0800;
 					};
 				};
 			};
@@ -708,9 +711,9 @@
 				7CA4813A19A2EA8D0030B30D /* SwifterSampleOSX */,
 				7AE893E61C05127900A29F63 /* SwifteriOS */,
 				7AE893FA1C0512C400A29F63 /* SwifterMac */,
+				7CCD1BA81C8F84E60016D664 /* SwiftertvOS */,
 				7CCD875B1C66099B0068099B /* SwifteriOSTests */,
 				7CCD87781C660EA30068099B /* SwifterOSXTests */,
-				7CCD1BA81C8F84E60016D664 /* SwiftertvOS */,
 			);
 		};
 /* End PBXProject section */
@@ -1043,6 +1046,7 @@
 				SDKROOT = macosx;
 				SKIP_INSTALL = YES;
 				SWIFT_OPTIMIZATION_LEVEL = "-Onone";
+				SWIFT_VERSION = 3.0;
 				VERSIONING_SYSTEM = "apple-generic";
 				VERSION_INFO_PREFIX = "";
 			};
@@ -1074,6 +1078,7 @@
 				SDKROOT = macosx;
 				SKIP_INSTALL = YES;
 				SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
+				SWIFT_VERSION = 3.0;
 				VERSIONING_SYSTEM = "apple-generic";
 				VERSION_INFO_PREFIX = "";
 			};
@@ -1221,6 +1226,7 @@
 				SDKROOT = macosx;
 				SWIFT_OBJC_BRIDGING_HEADER = "";
 				SWIFT_OPTIMIZATION_LEVEL = "-Onone";
+				SWIFT_VERSION = 3.0;
 			};
 			name = Debug;
 		};
@@ -1237,6 +1243,7 @@
 				SDKROOT = macosx;
 				SWIFT_OBJC_BRIDGING_HEADER = "";
 				SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
+				SWIFT_VERSION = 3.0;
 			};
 			name = Release;
 		};
@@ -1379,6 +1386,7 @@
 				PRODUCT_BUNDLE_IDENTIFIER = pl.kolakowski.SwifterOSXTests;
 				PRODUCT_NAME = "$(TARGET_NAME)";
 				SDKROOT = macosx;
+				SWIFT_VERSION = 3.0;
 			};
 			name = Debug;
 		};
@@ -1398,6 +1406,7 @@
 				PRODUCT_NAME = "$(TARGET_NAME)";
 				SDKROOT = macosx;
 				SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
+				SWIFT_VERSION = 3.0;
 			};
 			name = Release;
 		};

+ 1 - 1
XCode/SwifterSampleOSX/main.swift

@@ -10,7 +10,7 @@ import Swifter
 do {
     let server: HttpServer = demoServer(try File.currentWorkingDirectory())
     server["/testAfterBaseRoute"] = { request in
-        return .OK(.Html("ok !"))
+        return .ok(.html("ok !"))
     }
     if #available(OSX 10.10, *) {
         try server.start(9080)

+ 13 - 13
XCode/SwifterTestsCommon/SwifterTestsHttpParser.swift

@@ -25,7 +25,7 @@ class SwifterTestsHttpParser: XCTestCase {
                 offset = offset + 1
                 return value
             }
-            throw SocketError.RecvFailed("")
+            throw SocketError.recvFailed("")
         }
     }
     
@@ -33,60 +33,60 @@ class SwifterTestsHttpParser: XCTestCase {
         let parser = HttpParser()
         
         do {
-            try parser.readHttpRequest(TestSocket(""))
+            let _ = try parser.readHttpRequest(TestSocket(""))
             XCTAssert(false, "Parser should throw an error if socket is empty.")
         } catch { }
 
         do {
-            try parser.readHttpRequest(TestSocket("12345678"))
+            let _ = 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"))
+            let _ = 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"))
+            let _ = 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"))
+            let _ = 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"))
+            let _ = 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"))
+            let _ = 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"))
+            let _ = 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"))
+            let _ = 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"))
+            let _ = 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"))
+            let _ = 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.")
         } catch { }
         
@@ -102,4 +102,4 @@ class SwifterTestsHttpParser: XCTestCase {
         XCTAssert(r?.headers["header1"] == "1", "Parser should extract multiple headers from the request.")
         XCTAssert(r?.headers["header2"] == "2", "Parser should extract multiple headers from the request.")
     }
-}
+}

+ 5 - 5
XCode/SwifterTestsCommon/SwifterTestsHttpRouter.swift

@@ -16,7 +16,7 @@ class SwifterTestsHttpRouter: XCTestCase {
         let router = HttpRouter()
         
         router.register(nil, path: "/", handler: { r in
-            return .OK(.Html("OK"))
+            return .ok(.html("OK"))
         })
         
         XCTAssert(router.route(nil, path: "/") != nil)
@@ -27,7 +27,7 @@ class SwifterTestsHttpRouter: XCTestCase {
         let router = HttpRouter()
         
         router.register(nil, path: "/a/b/c/d", handler: { r in
-            return .OK(.Html("OK"))
+            return .ok(.html("OK"))
         })
         
         XCTAssert(router.route(nil, path: "/") == nil)
@@ -42,7 +42,7 @@ class SwifterTestsHttpRouter: XCTestCase {
         let router = HttpRouter()
         
         router.register(nil, path: "/a/*/c/d", handler: { r in
-            return .OK(.Html("OK"))
+            return .ok(.html("OK"))
         })
         
         XCTAssert(router.route(nil, path: "/") == nil)
@@ -58,7 +58,7 @@ class SwifterTestsHttpRouter: XCTestCase {
         let router = HttpRouter()
         
         router.register(nil, path: "/a/:arg1/:arg2/b/c/d/:arg3", handler: { r in
-            return .OK(.Html("OK"))
+            return .ok(.html("OK"))
         })
         
         XCTAssert(router.route(nil, path: "/") == nil)
@@ -74,7 +74,7 @@ class SwifterTestsHttpRouter: XCTestCase {
         let router = HttpRouter()
         
         router.register(nil, path: "/a/**/e/f/g", handler: { r in
-            return .OK(.Html("OK"))
+            return .ok(.html("OK"))
         })
         
         XCTAssert(router.route(nil, path: "/") == nil)

+ 4 - 4
XCode/SwifterTestsCommon/SwifterTestsSQLite.swift

@@ -15,7 +15,7 @@ class SwifterTestsSQLite: XCTestCase {
         
         print(try? File.currentWorkingDirectory())
         
-        guard let databsePath = try? File.currentWorkingDirectory() + "/" + "test_\(Int64(NSDate().timeIntervalSince1970*1000)).db" else {
+        guard let databsePath = try? File.currentWorkingDirectory() + "/" + "test_\(Int64(Date().timeIntervalSince1970*1000)).db" else {
             XCTAssert(false, "Could not find a path for a database file.")
             return
         }
@@ -23,7 +23,7 @@ class SwifterTestsSQLite: XCTestCase {
         do {
             let database = try SQLite.open(databsePath)
             XCTAssert(true, "Opening the database should not throw any exceptions.")
-            try database.close()
+            database.close()
         } catch {
             XCTAssert(false, "Opening the database should not throw any exceptions.")
         }
@@ -33,7 +33,7 @@ class SwifterTestsSQLite: XCTestCase {
             try database.exec("CREATE TABLE swifter_tests (title TEXT, description TEXT);")
             try database.exec("INSERT INTO swifter_tests VALUES (\"Test1\", \"Test1 Description\");")
             try database.exec("INSERT INTO swifter_tests VALUES (\"Test2\", \"Test2 Description\");")
-            try database.close()
+            database.close()
         } catch {
             XCTAssert(false, "Database manipulation should not throw any exceptions: \(error).")
         }
@@ -42,7 +42,7 @@ class SwifterTestsSQLite: XCTestCase {
             let database = try SQLite.open(databsePath)
             
             var counter = 0
-            for row in try database.enumerate("SELECT * FROM swifter_tests;") {
+            for _ in try database.enumerate("SELECT * FROM swifter_tests;") {
                 counter = counter + 1
             }
             XCTAssert(counter == 2, "Database should have two rows.")

+ 12 - 12
XCode/SwifterTestsCommon/SwifterTestsWebSocketSession.swift

@@ -25,7 +25,7 @@ class SwifterTestsWebSocketSession: XCTestCase {
                 offset = offset + 1
                 return value
             }
-            throw SocketError.RecvFailed("")
+            throw SocketError.recvFailed("")
         }
     }
     
@@ -33,7 +33,7 @@ class SwifterTestsWebSocketSession: XCTestCase {
         
         do {
             let session = WebSocketSession(TestSocket([0]))
-            try session.readFrame()
+            let _ = try session.readFrame()
             XCTAssert(false, "Parser should throw an error if socket has not enough data for a frame.")
         } catch {
             XCTAssert(true, "Parser should throw an error if socket has not enough data for a frame.")
@@ -41,9 +41,9 @@ class SwifterTestsWebSocketSession: XCTestCase {
         
         do {
             let session = WebSocketSession(TestSocket([0b0000_0001, 0b0000_0000, 0, 0, 0, 0]))
-            try session.readFrame()
+            let _ = try session.readFrame()
             XCTAssert(false, "Parser should not accept unmasked frames.")
-        } catch WebSocketSession.Error.UnMaskedFrame {
+        } catch WebSocketSession.Error.unMaskedFrame {
             XCTAssert(true, "Parse should throw UnMaskedFrame error for unmasked message.")
         } catch {
             XCTAssert(false, "Parse should throw UnMaskedFrame error for unmasked message.")
@@ -60,7 +60,7 @@ class SwifterTestsWebSocketSession: XCTestCase {
         do {
             let session = WebSocketSession(TestSocket([0b0000_0000, 0b1000_0000, 0, 0, 0, 0]))
             let frame = try session.readFrame()
-            XCTAssertEqual(frame.opcode, WebSocketSession.OpCode.Continue, "Parser should accept Continue opcode.")
+            XCTAssertEqual(frame.opcode, WebSocketSession.OpCode.continue, "Parser should accept Continue opcode.")
         } catch {
             XCTAssertTrue(true, "Parser should accept Continue opcode without any errors.")
         }
@@ -68,7 +68,7 @@ class SwifterTestsWebSocketSession: XCTestCase {
         do {
             let session = WebSocketSession(TestSocket([0b0000_0001, 0b1000_0000, 0, 0, 0, 0]))
             let frame = try session.readFrame()
-            XCTAssertEqual(frame.opcode, WebSocketSession.OpCode.Text, "Parser should accept Text opcode.")
+            XCTAssertEqual(frame.opcode, WebSocketSession.OpCode.text, "Parser should accept Text opcode.")
         } catch {
             XCTAssert(false, "Parser should accept Text opcode without any errors.")
         }
@@ -76,7 +76,7 @@ class SwifterTestsWebSocketSession: XCTestCase {
         do {
             let session = WebSocketSession(TestSocket([0b0000_0010, 0b1000_0000, 0, 0, 0, 0]))
             let frame = try session.readFrame()
-            XCTAssertEqual(frame.opcode, WebSocketSession.OpCode.Binary, "Parser should accept Binary opcode.")
+            XCTAssertEqual(frame.opcode, WebSocketSession.OpCode.binary, "Parser should accept Binary opcode.")
         } catch {
             XCTAssert(false, "Parser should accept Binary opcode without any errors.")
         }
@@ -84,7 +84,7 @@ class SwifterTestsWebSocketSession: XCTestCase {
         do {
             let session = WebSocketSession(TestSocket([0b0000_1000, 0b1000_0000, 0, 0, 0, 0]))
             let frame = try session.readFrame()
-            XCTAssertEqual(frame.opcode, WebSocketSession.OpCode.Close, "Parser should accept Close opcode.")
+            XCTAssertEqual(frame.opcode, WebSocketSession.OpCode.close, "Parser should accept Close opcode.")
         } catch {
             XCTAssert(false, "Parser should accept Close opcode without any errors.")
         }
@@ -92,7 +92,7 @@ class SwifterTestsWebSocketSession: XCTestCase {
         do {
             let session = WebSocketSession(TestSocket([0b0000_1001, 0b1000_0000, 0, 0, 0, 0]))
             let frame = try session.readFrame()
-            XCTAssertEqual(frame.opcode, WebSocketSession.OpCode.Ping, "Parser should accept Ping opcode.")
+            XCTAssertEqual(frame.opcode, WebSocketSession.OpCode.ping, "Parser should accept Ping opcode.")
         } catch {
             XCTAssert(false, "Parser should accept Ping opcode without any errors.")
         }
@@ -100,7 +100,7 @@ class SwifterTestsWebSocketSession: XCTestCase {
         do {
             let session = WebSocketSession(TestSocket([0b0000_1010, 0b1000_0000, 0, 0, 0, 0]))
             let frame = try session.readFrame()
-            XCTAssertEqual(frame.opcode, WebSocketSession.OpCode.Pong, "Parser should accept Pong opcode.")
+            XCTAssertEqual(frame.opcode, WebSocketSession.OpCode.pong, "Parser should accept Pong opcode.")
         } catch {
             XCTAssert(false, "Parser should accept Pong opcode without any errors.")
         }
@@ -108,9 +108,9 @@ class SwifterTestsWebSocketSession: XCTestCase {
         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]))
-                try session.readFrame()
+                let _ = try session.readFrame()
                 XCTAssert(false, "Parse should throw an error for unknown opcode: \(opcode)")
-            } catch WebSocketSession.Error.UnknownOpCode(_) {
+            } catch WebSocketSession.Error.unknownOpCode(_) {
                 XCTAssert(true, "Parse should throw UnknownOpCode error for unknown opcode.")
             } catch {
                 XCTAssert(false, "Parse should throw UnknownOpCode error for unknown opcode (was \(error)).")