diff --git a/.travis.yml b/.travis.yml index f1c6f3e..61b6a82 100644 --- a/.travis.yml +++ b/.travis.yml @@ -19,7 +19,11 @@ matrix: sudo: required - os: Linux dist: trusty - env: SWIFT_SNAPSHOT_NAME="https://swift.org/builds/swift-4.2-branch/ubuntu1404/swift-4.2-DEVELOPMENT-SNAPSHOT-2018-07-24-a/swift-4.2-DEVELOPMENT-SNAPSHOT-2018-07-24-a-ubuntu14.04.tar.gz" + env: SWIFT_SNAPSHOT_NAME="https://swift.org/builds/swift-4.2.3-release/ubuntu1404/swift-4.2.3-RELEASE/swift-4.2.3-RELEASE-ubuntu14.04.tar.gz" + sudo: required + - os: Linux + dist: trusty + env: SWIFT_SNAPSHOT_NAME="https://swift.org/builds/swift-5.0-branch/ubuntu1404/swift-5.0-DEVELOPMENT-SNAPSHOT-2019-03-10-a/swift-5.0-DEVELOPMENT-SNAPSHOT-2019-03-10-a-ubuntu14.04.tar.gz" sudo: required - os: osx osx_image: xcode8.3 @@ -29,6 +33,10 @@ matrix: osx_image: xcode9.3 - os: osx osx_image: xcode9.4 + - os: osx + osx_image: xcode10.1 + - os: osx + osx_image: xcode10.2 before_install: - ./.travis.d/before-install.sh diff --git a/Noze.io.xcodeproj/project.pbxproj b/Noze.io.xcodeproj/project.pbxproj index 5693279..4364eef 100644 --- a/Noze.io.xcodeproj/project.pbxproj +++ b/Noze.io.xcodeproj/project.pbxproj @@ -5220,7 +5220,7 @@ }; buildConfigurationList = E835BFAB1B4D4CFB00288839 /* Build configuration list for PBXProject "Noze.io" */; compatibilityVersion = "Xcode 3.2"; - developmentRegion = English; + developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( en, @@ -7578,54 +7578,10 @@ isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_SUSPICIOUS_MOVES = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - CODE_SIGN_IDENTITY = "-"; - COMBINE_HIDPI_IMAGES = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = dwarf; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; INFOPLIST_FILE = Tests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; - MACOSX_DEPLOYMENT_TARGET = 10.12; - MTL_ENABLE_DEBUG_INFO = YES; - ONLY_ACTIVE_ARCH = YES; PRODUCT_BUNDLE_IDENTIFIER = io.noze.tests.NozeCryptoTests; PRODUCT_NAME = "$(TARGET_NAME)"; - SDKROOT = macosx; SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 3.0; }; name = AppKitDebug; }; @@ -7633,46 +7589,9 @@ isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_SUSPICIOUS_MOVES = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - CODE_SIGN_IDENTITY = "-"; - COMBINE_HIDPI_IMAGES = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; INFOPLIST_FILE = Tests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; - MACOSX_DEPLOYMENT_TARGET = 10.12; - MTL_ENABLE_DEBUG_INFO = NO; PRODUCT_BUNDLE_IDENTIFIER = io.noze.tests.NozeCryptoTests; PRODUCT_NAME = "$(TARGET_NAME)"; - SDKROOT = macosx; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; - SWIFT_VERSION = 3.0; }; name = UIKitDebug; }; @@ -7680,46 +7599,9 @@ isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_SUSPICIOUS_MOVES = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - CODE_SIGN_IDENTITY = "-"; - COMBINE_HIDPI_IMAGES = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; INFOPLIST_FILE = Tests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; - MACOSX_DEPLOYMENT_TARGET = 10.12; - MTL_ENABLE_DEBUG_INFO = NO; PRODUCT_BUNDLE_IDENTIFIER = io.noze.tests.NozeCryptoTests; PRODUCT_NAME = "$(TARGET_NAME)"; - SDKROOT = macosx; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; - SWIFT_VERSION = 3.0; }; name = AppKitRelease; }; @@ -7727,46 +7609,9 @@ isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_SUSPICIOUS_MOVES = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - CODE_SIGN_IDENTITY = "-"; - COMBINE_HIDPI_IMAGES = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; INFOPLIST_FILE = Tests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; - MACOSX_DEPLOYMENT_TARGET = 10.12; - MTL_ENABLE_DEBUG_INFO = NO; PRODUCT_BUNDLE_IDENTIFIER = io.noze.tests.NozeCryptoTests; PRODUCT_NAME = "$(TARGET_NAME)"; - SDKROOT = macosx; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; - SWIFT_VERSION = 3.0; }; name = UIKitRelease; }; diff --git a/Package@swift-5.swift b/Package@swift-5.swift new file mode 100644 index 0000000..c849263 --- /dev/null +++ b/Package@swift-5.swift @@ -0,0 +1,74 @@ +// swift-tools-version:5.0 +import PackageDescription + +let package = Package( + name: "NozeIO", + products: [ + .library(name: "Freddy", targets: ["Freddy"]), + .library(name: "CryptoSwift", targets: ["CryptoSwift"]), + .library(name: "http_parser", targets: ["http_parser"]), + .library(name: "base64", targets: ["base64"]), + .library(name: "mustache", targets: ["mustache"]), + .library(name: "xsys", targets: ["xsys"]), + .library(name: "core", targets: ["core"]), + .library(name: "leftpad", targets: ["leftpad"]), + .library(name: "events", targets: ["events"]), + .library(name: "streams", targets: ["streams"]), + .library(name: "json", targets: ["json"]), + .library(name: "fs", targets: ["fs"]), + .library(name: "crypto", targets: ["crypto"]), + .library(name: "dns", targets: ["dns"]), + .library(name: "net", targets: ["net"]), + .library(name: "dgram", targets: ["dgram"]), + .library(name: "process", targets: ["process"]), + .library(name: "console", targets: ["console"]), + .library(name: "http", targets: ["http"]), + .library(name: "child_process", targets: ["child_process"]), + .library(name: "connect", targets: ["connect"]), + .library(name: "express", targets: ["express"]), + .library(name: "redis", targets: ["redis"]), + .library(name: "cows", targets: ["cows"]), + ], + dependencies: [], + targets: [ + .target(name:"Freddy"), + .target(name:"CryptoSwift"), + .target(name:"http_parser"), + .target(name:"base64"), + .target(name:"mustache"), + + .target(name:"xsys"), + .target(name:"core", dependencies: [ "xsys" ]), + .target(name:"leftpad", dependencies: [ "core" ]), + .target(name:"events", dependencies: [ "core" ]), + .target(name:"streams", dependencies: [ "core", "events" ]), + .target(name:"json", dependencies: [ "core", "streams", "Freddy","fs" ]), + .target(name:"fs", dependencies: [ "core", "xsys", "events", "streams" ]), + .target(name:"crypto", + dependencies: [ "core", "xsys", "events", "streams", "CryptoSwift"]), + .target(name:"dns", dependencies: [ "core", "xsys" ]), + .target(name:"net", + dependencies: [ "core", "xsys", "events", "streams", "fs", "dns" ]), + .target(name: "dgram", dependencies: [ "net" ]), + .target(name: "process", + dependencies: [ "core", "xsys", "streams", "fs" ]), + .target(name: "console", + dependencies: [ "core", "xsys", "events", "streams", "process" ]), + .target(name: "http", + dependencies: [ "http_parser", "core", "events", "streams", "net", + "console" ]), + .target(name: "child_process", + dependencies: [ "core", "xsys", "streams", "process", "fs" ]), + .target(name: "connect", + dependencies: [ "core", "xsys", "events", "streams", "http", + "console", "Freddy", "json", "leftpad" ]), + .target(name: "express", + dependencies: [ "core", "xsys", "events", "streams", "http", + "connect", "mustache" ]), + .target(name: "redis", + dependencies: [ "core", "xsys", "events", "streams", "net", + "console" ]), + .target(name: "cows", dependencies: [ "core", "xsys" ]) + ] +) + diff --git a/README.md b/README.md index fee6ecd..4707a78 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,7 @@ ![Swift3](https://img.shields.io/badge/swift-3-blue.svg) ![Swift4](https://img.shields.io/badge/swift-4-blue.svg) +![Swift5](https://img.shields.io/badge/swift-5-blue.svg) ![macOS](https://img.shields.io/badge/os-macOS-green.svg?style=flat) ![iOS](https://img.shields.io/badge/os-iOS-green.svg?style=flat) ![Linux](https://img.shields.io/badge/os-tuxOS-green.svg?style=flat) diff --git a/Samples/miniirc/Channel.swift b/Samples/miniirc/Channel.swift index 9c9f983..9499544 100644 --- a/Samples/miniirc/Channel.swift +++ b/Samples/miniirc/Channel.swift @@ -48,7 +48,11 @@ class Channel { } func part(session s: Session) { - let idxO = sessions.index(where: { $0 === s }) + #if swift(>=5) + let idxO = sessions.firstIndex(where: { $0 === s }) + #else + let idxO = sessions.index(where: { $0 === s }) + #endif if let idx = idxO { print("leaving channel \(name): \(s)") sessions.remove(at: idx) diff --git a/Samples/miniirc/Session.swift b/Samples/miniirc/Session.swift index 6a8b386..abdcb35 100644 --- a/Samples/miniirc/Session.swift +++ b/Samples/miniirc/Session.swift @@ -115,9 +115,16 @@ class Session { for channelName in channels { if let channel = nameToChannel[channelName] { channel.part(session: self) - if let idx = channelsJoined.index(where: { $0 === channel }) { - channelsJoined.remove(at: idx) - } + #if swift(>=5) + if let idx = channelsJoined.firstIndex(where: { $0 === channel }) + { + channelsJoined.remove(at: idx) + } + #else + if let idx = channelsJoined.index(where: { $0 === channel }) { + channelsJoined.remove(at: idx) + } + #endif } } diff --git a/Sources/CryptoSwift/Updatable.swift b/Sources/CryptoSwift/Updatable.swift index ea76688..2779d51 100644 --- a/Sources/CryptoSwift/Updatable.swift +++ b/Sources/CryptoSwift/Updatable.swift @@ -49,48 +49,48 @@ public protocol Updatable { public extension Updatable { - public mutating func update(withBytes bytes: ArraySlice, isLast: Bool = false, output: (_ bytes: Array) -> Void) throws { + mutating func update(withBytes bytes: ArraySlice, isLast: Bool = false, output: (_ bytes: Array) -> Void) throws { let processed = try update(withBytes: bytes, isLast: isLast) if !processed.isEmpty { output(processed) } } - public mutating func finish(withBytes bytes: ArraySlice) throws -> Array { + mutating func finish(withBytes bytes: ArraySlice) throws -> Array { return try update(withBytes: bytes, isLast: true) } - public mutating func finish() throws -> Array { + mutating func finish() throws -> Array { return try update(withBytes: [], isLast: true) } - public mutating func finish(withBytes bytes: ArraySlice, output: (_ bytes: Array) -> Void) throws { + mutating func finish(withBytes bytes: ArraySlice, output: (_ bytes: Array) -> Void) throws { let processed = try update(withBytes: bytes, isLast: true) if !processed.isEmpty { output(processed) } } - public mutating func finish(output: (Array) -> Void) throws { + mutating func finish(output: (Array) -> Void) throws { try finish(withBytes: [], output: output) } } public extension Updatable { - public mutating func update(withBytes bytes: Array, isLast: Bool = false) throws -> Array { + mutating func update(withBytes bytes: Array, isLast: Bool = false) throws -> Array { return try update(withBytes: bytes.slice, isLast: isLast) } - public mutating func update(withBytes bytes: Array, isLast: Bool = false, output: (_ bytes: Array) -> Void) throws { + mutating func update(withBytes bytes: Array, isLast: Bool = false, output: (_ bytes: Array) -> Void) throws { return try update(withBytes: bytes.slice, isLast: isLast, output: output) } - public mutating func finish(withBytes bytes: Array) throws -> Array { + mutating func finish(withBytes bytes: Array) throws -> Array { return try finish(withBytes: bytes.slice) } - public mutating func finish(withBytes bytes: Array, output: (_ bytes: Array) -> Void) throws { + mutating func finish(withBytes bytes: Array, output: (_ bytes: Array) -> Void) throws { return try finish(withBytes: bytes.slice, output: output) } } diff --git a/Sources/child_process/ChildProcess.swift b/Sources/child_process/ChildProcess.swift index 3d8aa75..b9f4bb4 100644 --- a/Sources/child_process/ChildProcess.swift +++ b/Sources/child_process/ChildProcess.swift @@ -124,7 +124,11 @@ public class ChildProcess : ErrorEmitter { if didRetainCore { core.module.release(); didRetainCore = false } - let myIdx = activeChildProcesses.index(where: { $0 === self }) + #if swift(>=5) + let myIdx = activeChildProcesses.firstIndex(where: { $0 === self }) + #else + let myIdx = activeChildProcesses.index(where: { $0 === self }) + #endif if let idx = myIdx { activeChildProcesses.remove(at: idx) } diff --git a/Sources/connect/BodyParser.swift b/Sources/connect/BodyParser.swift index 954bf59..594b00f 100644 --- a/Sources/connect/BodyParser.swift +++ b/Sources/connect/BodyParser.swift @@ -48,7 +48,7 @@ public enum BodyParserBody { public extension BodyParserBody { - public subscript(key : String) -> Any? { + subscript(key : String) -> Any? { get { switch self { case .URLEncoded(let dict): return dict[key] @@ -57,7 +57,7 @@ public extension BodyParserBody { } } } - public subscript(string key : String) -> String { + subscript(string key : String) -> String { get { switch self { case .URLEncoded(let dict): @@ -115,7 +115,7 @@ public enum BodyParserError : Error { public extension IncomingMessage { - public var body : BodyParserBody { + var body : BodyParserBody { set { extra[bodyParser.requestKey] = newValue } @@ -154,7 +154,7 @@ public extension bodyParser { /// next() /// } /// - public static func json(options opts: Options = Options()) -> Middleware { + static func json(options opts: Options = Options()) -> Middleware { return { req, res, next in guard typeIs(req, [ "json" ]) != nil else { next(); return } @@ -177,7 +177,7 @@ public extension bodyParser { public extension bodyParser { - public static func raw(options opts: Options = Options()) -> Middleware { + static func raw(options opts: Options = Options()) -> Middleware { return { req, res, next in // lame, should be streaming _ = req | concat { bytes in @@ -187,7 +187,7 @@ public extension bodyParser { } } - public static func text(options opts: Options = Options()) -> Middleware { + static func text(options opts: Options = Options()) -> Middleware { return { req, res, next in // text/plain, text/html etc // TODO: properly process charset parameter, this assumes UTF-8 @@ -208,9 +208,7 @@ public extension bodyParser { public extension bodyParser { - public static func urlencoded(options opts: Options = Options()) - -> Middleware - { + static func urlencoded(options opts: Options = Options()) -> Middleware { return { req, res, next in guard typeIs(req, [ "application/x-www-form-urlencoded" ]) != nil else { next() diff --git a/Sources/connect/Connect.swift b/Sources/connect/Connect.swift index 971065a..8cd6228 100644 --- a/Sources/connect/Connect.swift +++ b/Sources/connect/Connect.swift @@ -130,8 +130,8 @@ public class Connect { public extension Connect { @discardableResult - public func listen(_ port: Int?, backlog: Int = 512, - onListening cb : (( net.Server ) -> Void)? = nil) -> Self + func listen(_ port: Int?, backlog: Int = 512, + onListening cb : (( net.Server ) -> Void)? = nil) -> Self { let server = http.createServer(onRequest: self.handle) _ = server.listen(port, backlog: backlog, onListening: cb) diff --git a/Sources/connect/CookieParser.swift b/Sources/connect/CookieParser.swift index 9ba1d78..96bd3d1 100644 --- a/Sources/connect/CookieParser.swift +++ b/Sources/connect/CookieParser.swift @@ -38,7 +38,7 @@ public extension IncomingMessage { /// Returns the cookies embedded in the request. Note: Make sure to invoke /// the `cookieParser` middleware first, so that this property is actually /// filled. - public var cookies : [ String : String ] { + var cookies : [ String : String ] { get { // This concept is a little weird as so many thinks in Node. Why not just // parse the cookies on-demand? diff --git a/Sources/connect/Session.swift b/Sources/connect/Session.swift index 4e5b827..5a2381a 100644 --- a/Sources/connect/Session.swift +++ b/Sources/connect/Session.swift @@ -168,7 +168,7 @@ public extension IncomingMessage { return newSession } - public var session : Session { + var session : Session { guard let rawSN = extra[requestKey] else { return registerNewSession() } guard let session = rawSN as? Session else { diff --git a/Sources/console/Console.swift b/Sources/console/Console.swift index 23140d8..8a195a4 100644 --- a/Sources/console/Console.swift +++ b/Sources/console/Console.swift @@ -37,23 +37,23 @@ public protocol ConsoleType { public extension ConsoleType { // Actual logging funcs - public func error(_ msg: @autoclosure () -> String, _ values: Any?...) { + func error(_ msg: @autoclosure () -> String, _ values: Any?...) { primaryLog(.Error, msg, values) } - public func warn (_ msg: @autoclosure () -> String, _ values: Any?...) { + func warn (_ msg: @autoclosure () -> String, _ values: Any?...) { primaryLog(.Warn, msg, values) } - public func log (_ msg: @autoclosure () -> String, _ values: Any?...) { + func log (_ msg: @autoclosure () -> String, _ values: Any?...) { primaryLog(.Log, msg, values) } - public func info (_ msg: @autoclosure () -> String, _ values: Any?...) { + func info (_ msg: @autoclosure () -> String, _ values: Any?...) { primaryLog(.Info, msg, values) } - public func trace(_ msg: @autoclosure () -> String, _ values: Any?...) { + func trace(_ msg: @autoclosure () -> String, _ values: Any?...) { primaryLog(.Trace, msg, values) } - public func dir(_ obj: Any?) { + func dir(_ obj: Any?) { // TODO: implement more log("\(obj as Optional)") } diff --git a/Sources/core/CIDictionary.swift b/Sources/core/CIDictionary.swift index 55dcaa4..b4622e7 100644 --- a/Sources/core/CIDictionary.swift +++ b/Sources/core/CIDictionary.swift @@ -18,7 +18,7 @@ public extension Dictionary where Key : ExpressibleByStringLiteral { return nil } - public mutating func removeValue(forCIKey key: Key) -> Value? { + mutating func removeValue(forCIKey key: Key) -> Value? { if let realKey = self.lookupStoredKey(forCaseInsensitiveKey: key) { return self.removeValue(forKey: realKey) } @@ -27,7 +27,7 @@ public extension Dictionary where Key : ExpressibleByStringLiteral { } } - public subscript(ci key : Key) -> Value? { + subscript(ci key : Key) -> Value? { get { let realKey = self.lookupStoredKey(forCaseInsensitiveKey: key) return realKey != nil ? self[realKey!] : nil diff --git a/Sources/core/Logger.swift b/Sources/core/Logger.swift index 7f4bd8e..2428845 100644 --- a/Sources/core/Logger.swift +++ b/Sources/core/Logger.swift @@ -68,9 +68,9 @@ public class Logger : LoggerType { } } - public func log(message: @autoclosure () -> T, - filename: String? = #file, line: Int? = #line, - function: String? = #function) + private func _log(message: () -> T, + filename: String? = #file, line: Int? = #line, + function: String? = #function) { guard enabled else { return } @@ -85,12 +85,17 @@ public class Logger : LoggerType { if let cb = onAfterLog { cb(self) } } - - public func debug(message: @autoclosure () -> T, + public func log(message: () -> T, + filename: String? = #file, line: Int? = #line, + function: String? = #function) + { + _log(message: message, filename: filename, line: line, function: function) + } + public func debug(message: () -> T, filename: String? = #file, line: Int? = #line, function: String? = #function) { - log(message, filename: filename, line: line, function: function) + _log(message: message, filename: filename, line: line, function: function) } } @@ -112,9 +117,9 @@ public protocol LoggerType { func enter(filename: String?, line: Int?, function: String?) func leave(filename: String?, line: Int?, function: String?) - func log (message: @autoclosure () -> T, + func log (message: () -> T, filename: String?, line: Int?, function: String?) - func debug(message: @autoclosure () -> T, + func debug(message: () -> T, filename: String?, line: Int?, function: String?) } @@ -156,12 +161,12 @@ public protocol LameLogObjectType : CustomStringConvertible { public extension LameLogObjectType { - public func logState() { + func logState() { guard log.enabled else { return } log.debug("[\(logStateInfo)]") } - public var description : String { + var description : String { let t = type(of: self) return "<\(t):\(logStateInfo)>" } diff --git a/Sources/express/Express.swift b/Sources/express/Express.swift index 28f3a16..a42995b 100644 --- a/Sources/express/Express.swift +++ b/Sources/express/Express.swift @@ -88,9 +88,9 @@ public typealias ExpressEngine = ( public extension IncomingMessage { - public var app : Express? { return extra[appKey] as? Express } + var app : Express? { return extra[appKey] as? Express } - public var params : [ String : String ] { + var params : [ String : String ] { set { extra[paramsKey] = newValue } @@ -103,16 +103,16 @@ public extension IncomingMessage { } public extension ServerResponse { - public var app : Express? { return extra[appKey] as? Express } + var app : Express? { return extra[appKey] as? Express } - public var request : IncomingMessage? { + var request : IncomingMessage? { return extra[reqKey] as? IncomingMessage } } public extension Dictionary where Key : ExpressibleByStringLiteral { - public subscript(int key : Key) -> Int? { + subscript(int key : Key) -> Int? { guard let v = self[key] else { return nil } if let i = (v as? Int) { return i } return Int("\(v)") @@ -125,8 +125,8 @@ public extension Dictionary where Key : ExpressibleByStringLiteral { public extension Express { @discardableResult - public func listen(_ port: Int? = nil, backlog: Int = 512, - onListening cb : (( net.Server ) -> Void)? = nil) -> Self + func listen(_ port: Int? = nil, backlog: Int = 512, + onListening cb : (( net.Server ) -> Void)? = nil) -> Self { #if swift(>=3.1) let mo = self diff --git a/Sources/express/IncomingMessage.swift b/Sources/express/IncomingMessage.swift index 664e6a0..938055d 100644 --- a/Sources/express/IncomingMessage.swift +++ b/Sources/express/IncomingMessage.swift @@ -13,7 +13,7 @@ public extension IncomingMessage { // TODO: baseUrl, originalUrl, path // TODO: hostname, ip, ips, protocol - public func accepts(_ s: String) -> String? { + func accepts(_ s: String) -> String? { // TODO: allow array values guard let acceptHeader = (self.headers[ci: "accept"] as? String) else { return nil @@ -34,7 +34,7 @@ public extension IncomingMessage { } - public var xhr : Bool { + var xhr : Bool { guard let h = (headers[ci: "X-Requested-With"] as? String) else { return false } diff --git a/Sources/express/JSON.swift b/Sources/express/JSON.swift index 9fe3e8b..ad778b4 100644 --- a/Sources/express/JSON.swift +++ b/Sources/express/JSON.swift @@ -17,7 +17,7 @@ public extension ServerResponse { // TODO: Maybe we don't want to convert to a `JSON`, but rather stream real // object. - public func json(_ object: JSON) { + func json(_ object: JSON) { if canAssignContentType { setHeader("Content-Type", "application/json; charset=utf-8") } @@ -31,11 +31,11 @@ public extension ServerResponse { public extension ServerResponse { - public func json(_ object: JSONEncodable) { + func json(_ object: JSONEncodable) { json(object.toJSON()) } - public func json(_ object: Any?) { + func json(_ object: Any?) { if let o = object { if let jsonEncodable = (o as? JSONEncodable) { json(jsonEncodable) diff --git a/Sources/express/MiddlewareObject.swift b/Sources/express/MiddlewareObject.swift index a939321..9e1b88a 100644 --- a/Sources/express/MiddlewareObject.swift +++ b/Sources/express/MiddlewareObject.swift @@ -20,13 +20,13 @@ public protocol MiddlewareObject { public extension MiddlewareObject { - public var middleware: Middleware { + var middleware: Middleware { return { req, res, cb in self.handle(request: req, response: res, next: cb) } } - public var requestHandler: RequestEventCB { + var requestHandler: RequestEventCB { return { req, res in self.handle(request: req, response: res) { ( args: Any... ) in // essentially the final handler diff --git a/Sources/express/Render.swift b/Sources/express/Render.swift index ad89b21..312fe5a 100644 --- a/Sources/express/Render.swift +++ b/Sources/express/Render.swift @@ -16,7 +16,7 @@ public extension ServerResponse { // TODO: How do we get access to the application?? Need to attach to the // request? We need to retrieve values. - public func render(_ template: String, _ options : Any? = nil) { + func render(_ template: String, _ options : Any? = nil) { let res = self guard let app = self.app else { diff --git a/Sources/express/Route.swift b/Sources/express/Route.swift index 457c91b..cdd4320 100644 --- a/Sources/express/Route.swift +++ b/Sources/express/Route.swift @@ -279,7 +279,7 @@ private let routeKey = "io.noze.express.route" public extension IncomingMessage { - public var route : Route? { + var route : Route? { set { extra[routeKey] = newValue } get { return extra[routeKey] as? Route } } diff --git a/Sources/express/RouteKeeper.swift b/Sources/express/RouteKeeper.swift index aa8c8ab..dd4cd2d 100644 --- a/Sources/express/RouteKeeper.swift +++ b/Sources/express/RouteKeeper.swift @@ -20,50 +20,50 @@ public protocol RouteKeeper { public extension RouteKeeper { @discardableResult - public func use(_ cb: @escaping Middleware) -> Self { + func use(_ cb: @escaping Middleware) -> Self { add(route: Route(pattern: nil, method: nil, middleware: [cb])) return self } @discardableResult - public func use(_ p: String, _ cb: @escaping Middleware) -> Self { + func use(_ p: String, _ cb: @escaping Middleware) -> Self { add(route: Route(pattern: p, method: nil, middleware: [cb])) return self } @discardableResult - public func all(_ p: String, _ cb: @escaping Middleware) -> Self { + func all(_ p: String, _ cb: @escaping Middleware) -> Self { add(route: Route(pattern: p, method: nil, middleware: [cb])) return self } @discardableResult - public func get(_ p: String, _ cb: @escaping Middleware) -> Self { + func get(_ p: String, _ cb: @escaping Middleware) -> Self { add(route: Route(pattern: p, method: .GET, middleware: [cb])) return self } @discardableResult - public func post(_ p: String, _ cb: @escaping Middleware) -> Self { + func post(_ p: String, _ cb: @escaping Middleware) -> Self { add(route: Route(pattern: p, method: .POST, middleware: [cb])) return self } @discardableResult - public func head(_ p: String, _ cb: @escaping Middleware) -> Self { + func head(_ p: String, _ cb: @escaping Middleware) -> Self { add(route: Route(pattern: p, method: .HEAD, middleware: [cb])) return self } @discardableResult - public func put(_ p: String, _ cb: @escaping Middleware) -> Self { + func put(_ p: String, _ cb: @escaping Middleware) -> Self { add(route: Route(pattern: p, method: .PUT, middleware: [cb])) return self } @discardableResult - public func del(_ p: String, _ cb: @escaping Middleware) -> Self { + func del(_ p: String, _ cb: @escaping Middleware) -> Self { add(route: Route(pattern: p, method: .DELETE, middleware: [cb])) return self } @discardableResult - public func patch(_ p: String, _ cb: @escaping Middleware) -> Self { + func patch(_ p: String, _ cb: @escaping Middleware) -> Self { add(route: Route(pattern: p, method: .PATCH, middleware: [cb])) return self } @@ -76,47 +76,47 @@ public extension RouteKeeper { // app.use("/admin", admin) @discardableResult - public func use(_ middleware: MiddlewareObject) -> Self { + func use(_ middleware: MiddlewareObject) -> Self { return use(middleware.middleware) } @discardableResult - public func use(_ p: String, _ middleware: MiddlewareObject) -> Self { + func use(_ p: String, _ middleware: MiddlewareObject) -> Self { return use(p, middleware.middleware) } @discardableResult - public func all(_ p: String, _ middleware: MiddlewareObject) -> Self { + func all(_ p: String, _ middleware: MiddlewareObject) -> Self { return all(p, middleware.middleware) } @discardableResult - public func get(_ p: String, _ middleware: MiddlewareObject) -> Self { + func get(_ p: String, _ middleware: MiddlewareObject) -> Self { return get(p, middleware.middleware) } @discardableResult - public func post(_ p: String, _ middleware: MiddlewareObject) -> Self { + func post(_ p: String, _ middleware: MiddlewareObject) -> Self { return post(p, middleware.middleware) } @discardableResult - public func head(_ p: String, _ middleware: MiddlewareObject) -> Self { + func head(_ p: String, _ middleware: MiddlewareObject) -> Self { return head(p, middleware.middleware) } @discardableResult - public func put(_ p: String, _ middleware: MiddlewareObject) -> Self { + func put(_ p: String, _ middleware: MiddlewareObject) -> Self { return put(p, middleware.middleware) } @discardableResult - public func del(_ p: String, _ middleware: MiddlewareObject) -> Self { + func del(_ p: String, _ middleware: MiddlewareObject) -> Self { return del(p, middleware.middleware) } @discardableResult - public func patch(_ p: String, _ middleware: MiddlewareObject) -> Self { + func patch(_ p: String, _ middleware: MiddlewareObject) -> Self { return patch(p, middleware.middleware) } } diff --git a/Sources/express/ServerResponse.swift b/Sources/express/ServerResponse.swift index 79a7ca3..fe3c463 100644 --- a/Sources/express/ServerResponse.swift +++ b/Sources/express/ServerResponse.swift @@ -22,14 +22,14 @@ public extension ServerResponse { /// res.status(404).send("didn't find it") /// @discardableResult - public func status(_ code: Int) -> Self { + func status(_ code: Int) -> Self { statusCode = code return self } /// Set the HTTP status code and send the status description as the body. /// - public func sendStatus(_ code: Int) { + func sendStatus(_ code: Int) { let status = HTTPStatus(code) statusCode = code send(status.statusText) @@ -38,7 +38,7 @@ public extension ServerResponse { // MARK: - Sending Content - public func send(_ string: String) { + func send(_ string: String) { if canAssignContentType { var ctype = string.hasPrefix(" () ]) { + func format(handlers: [ String : () -> () ]) { var defaultHandler : (() -> ())? = nil guard let rq = request else { @@ -88,10 +88,10 @@ public extension ServerResponse { // MARK: - Header Accessor Renames - public func get(_ header: String) -> Any? { + func get(_ header: String) -> Any? { return getHeader(header) } - public func set(_ header: String, _ value: Any?) { + func set(_ header: String, _ value: Any?) { if let v = value { setHeader(header, v) } diff --git a/Sources/express/Settings.swift b/Sources/express/Settings.swift index 330779f..5f21cb8 100644 --- a/Sources/express/Settings.swift +++ b/Sources/express/Settings.swift @@ -15,14 +15,14 @@ public protocol SettingsHolder { public extension SettingsHolder { - public func enable(_ key: String) { + func enable(_ key: String) { set(key, true) } - public func disable(_ key: String) { + func disable(_ key: String) { set(key, false) } - public subscript(setting key : String) -> Any? { + subscript(setting key : String) -> Any? { get { return get(key) } set { set(key, newValue) } } diff --git a/Sources/fs/FileDescriptor.swift b/Sources/fs/FileDescriptor.swift index 2298990..83cbaad 100644 --- a/Sources/fs/FileDescriptor.swift +++ b/Sources/fs/FileDescriptor.swift @@ -169,9 +169,9 @@ extension FileDescriptor { // Socket Flags public extension FileDescriptor { - public var isDataAvailable: Bool { return poll(flag: POLLRDNORM) } + var isDataAvailable: Bool { return poll(flag: POLLRDNORM) } - public func poll(flag f: Int32) -> Bool { + func poll(flag f: Int32) -> Bool { let rc: Int32? = poll(events: f, timeout: 0) if let flags = rc { if (flags & f) != 0 { @@ -191,7 +191,7 @@ public extension FileDescriptor { // Swift doesn't allow let's in here?! var debugPoll : Bool { return false } - public func poll(events levents: Int32, timeout: UInt? = 0) -> Int32? { + func poll(events levents: Int32, timeout: UInt? = 0) -> Int32? { // This is declared as Int32 because the POLLRDNORM and such are guard isValid else { return nil } @@ -242,7 +242,13 @@ private func pollMaskToString(mask mask16: Int16) -> String { extension FileDescriptor: Equatable, Hashable { - public var hashValue: Int { return fd.hashValue } + #if swift(>=5) + public func hash(into hasher: inout Hasher) { + fd.hash(into: &hasher) + } + #else + public var hashValue: Int { return fd.hashValue } + #endif } diff --git a/Sources/fs/StatStruct.swift b/Sources/fs/StatStruct.swift index 5615b43..2318e6f 100644 --- a/Sources/fs/StatStruct.swift +++ b/Sources/fs/StatStruct.swift @@ -16,19 +16,19 @@ import xsys public extension xsys.stat_struct { // could be properties, but for consistency with Node ... - public func isFile() -> Bool { return (st_mode & S_IFMT) == S_IFREG } - public func isDirectory() -> Bool { return (st_mode & S_IFMT) == S_IFDIR } - public func isBlockDevice() -> Bool { return (st_mode & S_IFMT) == S_IFBLK } - public func isSymbolicLink() -> Bool { return (st_mode & S_IFMT) == S_IFLNK } - public func isFIFO() -> Bool { return (st_mode & S_IFMT) == S_IFIFO } - public func isSocket() -> Bool { return (st_mode & S_IFMT) == S_IFSOCK } + func isFile() -> Bool { return (st_mode & S_IFMT) == S_IFREG } + func isDirectory() -> Bool { return (st_mode & S_IFMT) == S_IFDIR } + func isBlockDevice() -> Bool { return (st_mode & S_IFMT) == S_IFBLK } + func isSymbolicLink() -> Bool { return (st_mode & S_IFMT) == S_IFLNK } + func isFIFO() -> Bool { return (st_mode & S_IFMT) == S_IFIFO } + func isSocket() -> Bool { return (st_mode & S_IFMT) == S_IFSOCK } - public func isCharacterDevice() -> Bool { + func isCharacterDevice() -> Bool { return (st_mode & S_IFMT) == S_IFCHR } - public var size : Int { return Int(st_size) } + var size : Int { return Int(st_size) } // TODO: we need a Date object, then we can do: diff --git a/Sources/http/HTTPConnection.swift b/Sources/http/HTTPConnection.swift index 568dccc..a954438 100644 --- a/Sources/http/HTTPConnection.swift +++ b/Sources/http/HTTPConnection.swift @@ -193,7 +193,7 @@ class HTTPConnection { } func onTimeout(socket: Socket) { // read OR write! - log.log(message: "socket did timeout \(socket)") + log.log("socket did timeout: \(socket)") emitDone() // what else? Do we have such on IncomingMessage/ServerResponse? } } diff --git a/Sources/http/HTTPStatus.swift b/Sources/http/HTTPStatus.swift index 8731c07..67c7b5f 100644 --- a/Sources/http/HTTPStatus.swift +++ b/Sources/http/HTTPStatus.swift @@ -54,7 +54,7 @@ extension HTTPStatus : RawRepresentable { public extension HTTPStatus { - public init(_ status: Int, _ text: String? = nil) { + init(_ status: Int, _ text: String? = nil) { switch status { case 200: self = .OK case 201: self = .Created @@ -121,7 +121,7 @@ public extension HTTPStatus { } } - public var status : Int { + var status : Int { // You ask: How to maintain the reverse list of the above? Emacs macro! switch self { @@ -186,7 +186,7 @@ public extension HTTPStatus { } } - public var statusText : String { + var statusText : String { switch self { case .Extension(_, let text): return text @@ -195,7 +195,7 @@ public extension HTTPStatus { } } - public static func text(forStatus status: Int) -> String { + static func text(forStatus status: Int) -> String { // FIXME: complete me for type safety ;-) switch status { diff --git a/Sources/http/QueryString.swift b/Sources/http/QueryString.swift index 58b3c5a..6762792 100644 --- a/Sources/http/QueryString.swift +++ b/Sources/http/QueryString.swift @@ -60,7 +60,11 @@ private func _parse(string s : String, // check key and whether it contains Zope style formats let keyPart = pairParts[0] - let fmtIdx = keyPart.index(of: ":") + #if swift(>=5) + let fmtIdx = keyPart.firstIndex(of: ":") + #else + let fmtIdx = keyPart.index(of: ":") + #endif let key : String let formats : String? @@ -204,9 +208,15 @@ public func _unescape(string: String) -> String { let s = string.characters #endif - guard s.index(of: "%") != nil || s.index(of: "+") != nil else { - return string - } + #if swift(>=5) + guard s.firstIndex(of: "%") != nil || s.firstIndex(of: "+") != nil else { + return string + } + #else + guard s.index(of: "%") != nil || s.index(of: "+") != nil else { + return string + } + #endif var newString = [ UInt8 ]() diff --git a/Sources/http/Server.swift b/Sources/http/Server.swift index 593650d..7f2c51d 100644 --- a/Sources/http/Server.swift +++ b/Sources/http/Server.swift @@ -86,7 +86,12 @@ open class Server: net.Server { func _connectionIsDone(c con: HTTPConnection) { log.enter(); defer { log.leave() } - let idx = httpConnections.index(where: { $0 === con }) // not Equatable + #if swift(>=5) + // not Equatable + let idx = httpConnections.firstIndex(where: { $0 === con }) + #else + let idx = httpConnections.index(where: { $0 === con }) // not Equatable + #endif assert(idx != nil) if let idx = idx { httpConnections.remove(at: idx) diff --git a/Sources/http/URL.swift b/Sources/http/URL.swift index fb926b6..2cdd908 100644 --- a/Sources/http/URL.swift +++ b/Sources/http/URL.swift @@ -126,7 +126,7 @@ public struct URL { public extension URL { // String representation - public func toString() -> String? { + func toString() -> String? { var us = "" var scheme = self.scheme @@ -175,7 +175,7 @@ public extension URL { // String representation public extension String { - public var withoutPercentEscapes : String { return percentUnescape(string: self) } + var withoutPercentEscapes : String { return percentUnescape(string: self) } } @@ -223,7 +223,7 @@ public extension URL { public extension URL { // /etc/services - public static func scheme(forPort port: Int) -> String? { + static func scheme(forPort port: Int) -> String? { // read /etc/services? but this doesn't have a proper 1337? switch port { case 7: return "echo" @@ -239,7 +239,7 @@ public extension URL { // /etc/services } } - public static func port(forScheme scheme: String) -> Int? { + static func port(forScheme scheme: String) -> Int? { // read /etc/services? but this doesn't have a proper 1337? switch scheme { case "echo": return 7; @@ -318,7 +318,9 @@ extension String { } private func index(string: String, c: Character) -> String.Index? { - #if swift(>=3.2) + #if swift(>=5) + return string.firstIndex(of: c) + #elseif swift(>=3.2) return string.index(of: c) #else return string.characters.index(of: c) diff --git a/Sources/http_parser/HTTPMethod.swift b/Sources/http_parser/HTTPMethod.swift index 437a9e9..03af523 100644 --- a/Sources/http_parser/HTTPMethod.swift +++ b/Sources/http_parser/HTTPMethod.swift @@ -131,7 +131,7 @@ public enum HTTPMethod : Int8 { public extension HTTPMethod { - public var method: String { + var method: String { switch self { case .GET: return "GET" case .HEAD: return "HEAD" @@ -180,7 +180,7 @@ public extension HTTPMethod { } } - public var isSafe: Bool? { // can't say for extension methods + var isSafe: Bool? { // can't say for extension methods switch self { case .GET, .HEAD, .OPTIONS: return true @@ -191,7 +191,7 @@ public extension HTTPMethod { } } - public var isIdempotent: Bool? { // can't say for extension methods + var isIdempotent: Bool? { // can't say for extension methods switch self { case .GET, .HEAD, .PUT, .DELETE, .OPTIONS: return true @@ -262,7 +262,7 @@ public extension HTTPMethod { static let csLINK = "LINK".makeCString() static let csUNLINK = "UNLINK".makeCString() - public var csMethod: UnsafePointer { + var csMethod: UnsafePointer { switch self { case .GET: return HTTPMethod.csGET case .HEAD: return HTTPMethod.csHEAD diff --git a/Sources/http_parser/http_parser.swift b/Sources/http_parser/http_parser.swift index d0c4a60..545d65d 100644 --- a/Sources/http_parser/http_parser.swift +++ b/Sources/http_parser/http_parser.swift @@ -375,9 +375,9 @@ public extension http_parser { /// Executes the parser. Returns number of parsed bytes. Sets /// `error` on error. - public mutating func execute(_ settings : http_parser_settings, - _ data: UnsafePointer?, _ len: size_t) - -> size_t + mutating func execute(_ settings : http_parser_settings, + _ data: UnsafePointer?, _ len: size_t) + -> size_t { /* We're in an error state. Don't bother doing anything. */ guard error == .OK else { return 0 } diff --git a/Sources/json/JSONWritableStream.swift b/Sources/json/JSONWritableStream.swift index 0f71aa4..5c8433d 100644 --- a/Sources/json/JSONWritableStream.swift +++ b/Sources/json/JSONWritableStream.swift @@ -26,7 +26,7 @@ private struct brigades { public extension GWritableStreamType where WriteType == UInt8 { // MARK: - JSON generator - public func writeJSON(string s: String) { + func writeJSON(string s: String) { let utf8 = s.utf8 // Well, in theory we could directly escape into the target buffer? No @@ -59,7 +59,7 @@ public extension GWritableStreamType where WriteType == UInt8 { _ = writev(buckets: [ buckets.quote, bucket, buckets.quote ], done: nil) } - public func writeJSON(object o: JSON) { + func writeJSON(object o: JSON) { // FIXME: This should be an on-demand stream switch o { diff --git a/Sources/json/Module.swift b/Sources/json/Module.swift index b327623..288ebc9 100644 --- a/Sources/json/Module.swift +++ b/Sources/json/Module.swift @@ -22,7 +22,7 @@ public typealias JSON = Freddy.JSON public extension JSON { - public static func parse(_ string: Swift.String) -> JSON? { + static func parse(_ string: Swift.String) -> JSON? { guard !string.isEmpty else { return nil } do { @@ -35,7 +35,7 @@ public extension JSON { } } - public static func parse(_ utf8: [ UInt8 ]) -> JSON? { + static func parse(_ utf8: [ UInt8 ]) -> JSON? { // this is a little weird, but yes, some people send GET requests with a // content-type: application/json ... guard !utf8.isEmpty else { return nil } diff --git a/Sources/json/Stringify.swift b/Sources/json/Stringify.swift index 0704757..1e5c0eb 100644 --- a/Sources/json/Stringify.swift +++ b/Sources/json/Stringify.swift @@ -11,7 +11,7 @@ public extension JSON { - public static func stringify(_ object: Any?) -> Swift.String { + static func stringify(_ object: Any?) -> Swift.String { guard let o = object else { return "null" } if let json = object as? JSON { @@ -25,7 +25,7 @@ public extension JSON { return JSON.String("\(o)").toString() } - public func toString() -> Swift.String { + func toString() -> Swift.String { var jsonString = "" jsonString.appendJSON(object: self) return jsonString @@ -35,7 +35,7 @@ public extension JSON { public extension String { - public mutating func appendJSON(string s: String) { + mutating func appendJSON(string s: String) { #if swift(>=3.2) let chars = s #else @@ -70,7 +70,7 @@ public extension String { self += "\"" } - public mutating func appendJSON(object o: JSON) { + mutating func appendJSON(object o: JSON) { switch o { case .Int (let v): self += "\(v)" case .String(let v): appendJSON(string: v) diff --git a/Sources/leftpad/Module.swift b/Sources/leftpad/Module.swift index 8ce6cb3..8260d9b 100644 --- a/Sources/leftpad/Module.swift +++ b/Sources/leftpad/Module.swift @@ -14,7 +14,7 @@ public let module = NozeLeftpad() public extension String { - public func leftpad(_ length: Int, c: Character = " ") -> String { + func leftpad(_ length: Int, c: Character = " ") -> String { #if swift(>=3.2) let oldLength = self.count #else diff --git a/Sources/mustache/MustacheNode.swift b/Sources/mustache/MustacheNode.swift index 9a32d34..c5dc67a 100644 --- a/Sources/mustache/MustacheNode.swift +++ b/Sources/mustache/MustacheNode.swift @@ -96,12 +96,12 @@ public enum MustacheNode { public extension MustacheNode { - public func render(object o: Any?, cb: ( String ) -> Void) { + func render(object o: Any?, cb: ( String ) -> Void) { let ctx = MustacheDefaultRenderingContext(o) render(inContext: ctx, cb: cb) } - public func render(object o: Any?) -> String { + func render(object o: Any?) -> String { let ctx = MustacheDefaultRenderingContext(o) render(inContext: ctx) return ctx.string @@ -113,14 +113,14 @@ public extension MustacheNode { nl.forEach { node in node.render(inContext: ctx) } } - public func render(inContext ctx: MustacheRenderingContext, + func render(inContext ctx: MustacheRenderingContext, cb: ( String ) -> Void) { render(inContext: ctx) // TODO: make async for partials cb(ctx.string) } - public func render(inContext ctx: MustacheRenderingContext) { + func render(inContext ctx: MustacheRenderingContext) { switch self { case .Empty: return @@ -165,7 +165,7 @@ public extension MustacheNode { } } - public func render(lambda cb : MustacheRenderingFunction, + func render(lambda cb : MustacheRenderingFunction, nodes nl : [ MustacheNode ], inContext ctx : MustacheRenderingContext) { @@ -196,7 +196,7 @@ public extension MustacheNode { public extension MustacheNode { - public var asMustacheString : String { + var asMustacheString : String { var s = String() self.append(toString: &s) return s @@ -205,8 +205,8 @@ public extension MustacheNode { public extension MustacheNode { - public func render(section tag: String, nodes : [ MustacheNode ], - inContext ctx: MustacheRenderingContext) + func render(section tag: String, nodes : [ MustacheNode ], + inContext ctx: MustacheRenderingContext) { let v = ctx.value(forTag: tag) guard let vv = v else { return } // nil @@ -267,7 +267,7 @@ public extension MustacheNode { public extension MustacheNode { - public func append(toString s : inout String) { + func append(toString s : inout String) { switch self { case .Empty: return @@ -303,7 +303,7 @@ public extension MustacheNode { public extension Sequence where Iterator.Element == MustacheNode { - public var asMustacheString : String { + var asMustacheString : String { var s = String() forEach { $0.append(toString: &s) } return s diff --git a/Sources/mustache/MustacheRenderingContext.swift b/Sources/mustache/MustacheRenderingContext.swift index d7a6bbb..f5705ac 100644 --- a/Sources/mustache/MustacheRenderingContext.swift +++ b/Sources/mustache/MustacheRenderingContext.swift @@ -38,11 +38,11 @@ public protocol MustacheRenderingContext { public extension MustacheRenderingContext { - public func value(forTag tag: String) -> Any? { + func value(forTag tag: String) -> Any? { return KeyValueCoding.value(forKeyPath: tag, inObject: cursor) } - public func retrievePartial(name n: String) -> MustacheNode? { + func retrievePartial(name n: String) -> MustacheNode? { return nil } } diff --git a/Sources/mustache/SimpleKVC.swift b/Sources/mustache/SimpleKVC.swift index 1dd775b..04a4c42 100644 --- a/Sources/mustache/SimpleKVC.swift +++ b/Sources/mustache/SimpleKVC.swift @@ -90,8 +90,8 @@ public struct KeyValueCoding { public extension KeyValueCoding { - public static func defaultValue(forKey k: String, inDictionary o: Any, - mirror: Mirror) -> Any? + static func defaultValue(forKey k: String, inDictionary o: Any, + mirror: Mirror) -> Any? { for ( _, pair ) in mirror.children { let pairMirror = Mirror(reflecting: pair) diff --git a/Sources/net/Server.swift b/Sources/net/Server.swift index 8035fd5..37b9e0c 100644 --- a/Sources/net/Server.swift +++ b/Sources/net/Server.swift @@ -221,7 +221,7 @@ open class Server : ErrorEmitter, LameLogObjectType { open func accept(socket s: Socket) { log.enter(); defer { log.leave() } - log.log("socket: \(socket)") + log.log("socket: \(s)") nextTick { // TODO: track connections in server diff --git a/Sources/net/SocketAddress.swift b/Sources/net/SocketAddress.swift index 5bd6f51..8bc39a9 100644 --- a/Sources/net/SocketAddress.swift +++ b/Sources/net/SocketAddress.swift @@ -26,7 +26,7 @@ public let INADDR_ANY = in_addr(s_addr: 0) */ public extension in_addr { - public static func make() -> in_addr { + static func make() -> in_addr { /* Disable the `init` API to please the 4.2 compiler in 4.0 mode. Was * ambiguous anyways. The default `in_addr.init` setting everything to 0 * should match INADDR_ANY.s_addr (AFAIK all zeros). @@ -36,7 +36,7 @@ public extension in_addr { return addr } - public init(string: String?) { + init(string: String?) { #if swift(>=4.1) self.init() #endif @@ -57,7 +57,7 @@ public extension in_addr { } } - public var asString: String { + var asString: String { if self == INADDR_ANY { return "*.*.*.*" } @@ -79,10 +79,17 @@ public func ==(lhs: in_addr, rhs: in_addr) -> Bool { extension in_addr : Equatable, Hashable { - public var hashValue: Int { - // Knuth? - return Int(UInt32(s_addr) * 2654435761 % (2^32)) - } + #if swift(>=5) + public func hash(into hasher: inout Hasher) { + // Knuth? + Int(UInt32(s_addr) * 2654435761 % (2^32)).hash(into: &hasher) + } + #else + public var hashValue: Int { + // Knuth? + return Int(UInt32(s_addr) * 2654435761 % (2^32)) + } + #endif } @@ -226,9 +233,15 @@ public func == (lhs: sockaddr_in, rhs: sockaddr_in) -> Bool { extension sockaddr_in: Equatable, Hashable { - public var hashValue: Int { - return sin_addr.hashValue + sin_port.hashValue - } + #if swift(>=5) + public func hash(into hasher: inout Hasher) { + (sin_addr.hashValue + sin_port.hashValue).hash(into: &hasher) + } + #else + public var hashValue: Int { + return sin_addr.hashValue + sin_port.hashValue + } + #endif } @@ -358,7 +371,7 @@ extension sockaddr_un: SocketAddress { public extension addrinfo { - public static func make() -> addrinfo { + static func make() -> addrinfo { var info = addrinfo() // This was plain `init` before. Careful w/ the default ctor! info.ai_flags = 0 // AI_CANONNAME, AI_PASSIVE, AI_NUMERICHOST @@ -372,7 +385,7 @@ public extension addrinfo { return info } - public init(flags: Int32, family: Int32 = xsys.AF_UNSPEC) { + init(flags: Int32, family: Int32 = xsys.AF_UNSPEC) { #if swift(>=4.1) // else: "Must use self.init because imported from C" self.init() #endif @@ -386,34 +399,34 @@ public extension addrinfo { ai_family = family // AF_INET or AF_INET6 or AF_UNSPEC } - public var hasNext : Bool { + var hasNext : Bool { return ai_next != nil } - public var next : addrinfo? { + var next : addrinfo? { return hasNext ? ai_next.pointee : nil } - public var canonicalName : String? { + var canonicalName : String? { guard ai_canonname != nil && ai_canonname[0] != 0 else { return nil } return String(validatingUTF8: ai_canonname) } - public var hasAddress : Bool { + var hasAddress : Bool { return ai_addr != nil } - public var isIPv4 : Bool { + var isIPv4 : Bool { return hasAddress && (ai_addr.pointee.sa_family == sa_family_t(sockaddr_in.domain)) } - public var addressIPv4 : sockaddr_in? { return address() } + var addressIPv4 : sockaddr_in? { return address() } /* Not working anymore in b4 public var addressIPv6 : sockaddr_in6? { return address() } */ - public func address() -> T? { + func address() -> T? { guard ai_addr != nil else { return nil } guard ai_addr.pointee.sa_family == sa_family_t(T.domain) else { return nil } @@ -422,7 +435,7 @@ public extension addrinfo { return aiptr?.pointee // copies the address to the return value } - public var dynamicAddress : SocketAddress? { + var dynamicAddress : SocketAddress? { guard hasAddress else { return nil } let airptr = UnsafeRawPointer(ai_addr) @@ -518,7 +531,7 @@ public extension sa_family_t { // Swift 2 : CustomStringConvertible, already imp?! // TBD: does Swift 2 still pick this up? - public var description : String { + var description : String { switch Int32(self) { case xsys.AF_UNSPEC: return "" case xsys.AF_INET: return "IPv4" diff --git a/Sources/process/Stdio.swift b/Sources/process/Stdio.swift index 367f98c..bcb7d52 100644 --- a/Sources/process/Stdio.swift +++ b/Sources/process/Stdio.swift @@ -34,7 +34,7 @@ private func createStdoutOrErr(fd lfd: Int32 = xsys.STDOUT_FILENO) public extension SourceStream where G: StdInSource { - public var isTTY : Bool { + var isTTY : Bool { return source.fd.isTTY } @@ -42,7 +42,7 @@ public extension SourceStream where G: StdInSource { public extension TargetStream where T: StdOutTarget { - public var isTTY : Bool { + var isTTY : Bool { return target.fd.isTTY } diff --git a/Sources/redis/RedisCommands.swift b/Sources/redis/RedisCommands.swift index dc4d8b8..2afd48a 100644 --- a/Sources/redis/RedisCommands.swift +++ b/Sources/redis/RedisCommands.swift @@ -21,14 +21,14 @@ public protocol RedisCommandTarget { // MARK: - Regular Keys GET, SET, KEYS etc public extension RedisCommandTarget { - public func get(_ key: String, _ cb: @escaping RedisReplyCB) { + func get(_ key: String, _ cb: @escaping RedisReplyCB) { let cmd = RedisCommand(command: "GET", RedisValue(bulkString: key), callback: cb) enqueue(command: cmd) } - public func keys(_ pattern: String = "*", _ cb: @escaping RedisArrayReplyCB) { + func keys(_ pattern: String = "*", _ cb: @escaping RedisArrayReplyCB) { // TBD: should this return `[String]?`? // and for people not using String keys, add a `rawKeys`? // Workaround: `keys.map { $0.stringValue! }` @@ -38,15 +38,13 @@ public extension RedisCommandTarget { enqueue(command: cmd) } - public func set(_ key: String, _ value: RedisValue, - _ cb: @escaping RedisReplyCB) - { + func set(_ key: String, _ value: RedisValue, _ cb: @escaping RedisReplyCB) { let cmd = RedisCommand(command: "SET", RedisValue(bulkString: key), value, callback: cb) enqueue(command: cmd) } - public func set(_ key: String, _ value: RedisValue) { + func set(_ key: String, _ value: RedisValue) { set(key, value) { err, value in if let err = err { console.error("could not set key", key, value, err) @@ -54,21 +52,21 @@ public extension RedisCommandTarget { } } - public func set(_ key: String, _ value: String, _ cb: @escaping RedisReplyCB) { + func set(_ key: String, _ value: String, _ cb: @escaping RedisReplyCB) { set(key, RedisValue(bulkString: value), cb) } - public func set(_ key: String, _ value: String) { + func set(_ key: String, _ value: String) { set(key, RedisValue(bulkString: value)) } - public func set(_ key: String, _ value: Int, _ cb: @escaping RedisReplyCB) { + func set(_ key: String, _ value: Int, _ cb: @escaping RedisReplyCB) { set(key, RedisValue(value), cb) } - public func set(_ key: String, _ value: Int) { + func set(_ key: String, _ value: Int) { set(key, RedisValue(value)) } - public func del(keys ks: [String], _ cb: @escaping RedisReplyCB) { + func del(keys ks: [String], _ cb: @escaping RedisReplyCB) { var values : [ RedisValue ] = [] values.append(RedisValue(bulkString: "DEL")) for key in ks { values.append(RedisValue(bulkString: key)) } @@ -76,17 +74,17 @@ public extension RedisCommandTarget { let cmd = RedisCommand(command: values, callback: cb) enqueue(command: cmd) } - public func del(keys ks: [String]) { + func del(keys ks: [String]) { del(keys: ks) { err, _ in if let err = err { console.error("could not delete keys", ks, err) } } } - public func del(_ keys: String..., cb: @escaping RedisReplyCB) { + func del(_ keys: String..., cb: @escaping RedisReplyCB) { del(keys: keys, cb) } - public func del(_ keys: String...) { + func del(_ keys: String...) { del(keys: keys) } } @@ -95,8 +93,8 @@ public extension RedisCommandTarget { // MARK: - Hashes HSET, HKEYS, etc public extension RedisCommandTarget { - public func hset(_ hashKey: String, _ key: String, _ value: RedisValue, - _ cb: @escaping RedisReplyCB) + func hset(_ hashKey: String, _ key: String, _ value: RedisValue, + _ cb: @escaping RedisReplyCB) { let cmd = RedisCommand(command: "HSET", RedisValue(bulkString: hashKey), @@ -104,7 +102,7 @@ public extension RedisCommandTarget { value, callback: cb) enqueue(command: cmd) } - public func hset(_ hashKey: String, _ key: String, _ value: RedisValue) { + func hset(_ hashKey: String, _ key: String, _ value: RedisValue) { hset(hashKey, key, value) { err, _ in if let err = err { console.error("could not hset key", hashKey, key, value, err) @@ -112,23 +110,23 @@ public extension RedisCommandTarget { } } - public func hset(_ hashKey: String, _ key: String, _ value: String, - _ cb: @escaping RedisReplyCB) + func hset(_ hashKey: String, _ key: String, _ value: String, + _ cb: @escaping RedisReplyCB) { hset(hashKey, key, RedisValue(bulkString: value), cb) } - public func hset(_ hashKey: String, _ key: String, _ value: String) { + func hset(_ hashKey: String, _ key: String, _ value: String) { hset(hashKey, key, RedisValue(bulkString: value)) } - public func hkeys(_ hashKey: String, _ cb: @escaping RedisArrayReplyCB) { + func hkeys(_ hashKey: String, _ cb: @escaping RedisArrayReplyCB) { let cmd = RedisCommand(command: "HKEYS", RedisValue(bulkString: hashKey), callback: makeArrayReplyHelper(callback: cb)) enqueue(command: cmd) } - public func hgetall(_ hashKey: String, _ cb: @escaping RedisHashReplyCB) { + func hgetall(_ hashKey: String, _ cb: @escaping RedisHashReplyCB) { let cmd = RedisCommand(command: "HGETALL", RedisValue(bulkString: hashKey), callback: makeHashReplyHelper(callback: cb)) @@ -148,14 +146,14 @@ public extension RedisCommandTarget { makeOHashReplyHelper(keys: keys, callback: cb)) enqueue(command: cmd) } - public func hmget(_ hashKey: String, _ k: String..., - cb: @escaping RedisOHashReplyCB) + func hmget(_ hashKey: String, _ k: String..., + cb: @escaping RedisOHashReplyCB) { _hmget(hashKey: hashKey, keys: k, cb) } - public func hmset(_ hashKey: String, _ hash: [ String : String ], - _ cb: @escaping RedisReplyCB) + func hmset(_ hashKey: String, _ hash: [ String : String ], + _ cb: @escaping RedisReplyCB) { // TODO: hmset which takes an array of key/value pairs instead of a dict var values : [ RedisValue ] = [] @@ -170,7 +168,7 @@ public extension RedisCommandTarget { let cmd = RedisCommand(command: values, callback:cb) enqueue(command: cmd) } - public func hmset(_ hashKey: String, _ hash: [ String : String ]) { + func hmset(_ hashKey: String, _ hash: [ String : String ]) { hmset(hashKey, hash) { err, _ in if let err = err { console.error("could not hmset", hashKey, hash, err) @@ -199,10 +197,10 @@ public extension RedisCommandTarget { enqueue(command: cmd) } - public func incr(_ key: String, by: Int = 1, _ cb: @escaping RedisIntReplyCB){ + func incr(_ key: String, by: Int = 1, _ cb: @escaping RedisIntReplyCB){ _enqueue(intByCommand: "INCR", key: key, by: by, cb) } - public func decr(_ key: String, by: Int = 1, _ cb: @escaping RedisIntReplyCB){ + func decr(_ key: String, by: Int = 1, _ cb: @escaping RedisIntReplyCB){ _enqueue(intByCommand: "DECR", key: key, by: by, cb) } @@ -212,7 +210,7 @@ public extension RedisCommandTarget { // MARK: - PubSub public extension RedisCommandTarget { - public func publish(_ channel: String, _ message: String) { + func publish(_ channel: String, _ message: String) { let cmd = RedisCommand(command: "PUBLISH", RedisValue(bulkString: channel), RedisValue(bulkString: message)) { diff --git a/Sources/redis/RedisValue.swift b/Sources/redis/RedisValue.swift index 19978cb..4d21b06 100644 --- a/Sources/redis/RedisValue.swift +++ b/Sources/redis/RedisValue.swift @@ -26,11 +26,11 @@ public enum RedisValue { public extension RedisValue { - public init(_ v: Int) { + init(_ v: Int) { self = .Integer(v) } - public init(bulkString s: String?) { + init(bulkString s: String?) { if let s = s { self = .BulkString(Swift.Array(s.utf8)) } @@ -39,11 +39,11 @@ public extension RedisValue { } } - public init(simpleString s: String) { + init(simpleString s: String) { self = .SimpleString(Swift.Array(s.utf8)) } - public var stringValue : String? { + var stringValue : String? { switch self { case .SimpleString(let cs): guard let s = String.decode(utf8: cs) else { return nil } @@ -61,7 +61,7 @@ public extension RedisValue { } } - public var intValue : Int? { + var intValue : Int? { switch self { // TBD: convert strings? case .Integer(let i): return i diff --git a/Sources/streams/GWritableStreamType.swift b/Sources/streams/GWritableStreamType.swift index f177938..1bc185d 100644 --- a/Sources/streams/GWritableStreamType.swift +++ b/Sources/streams/GWritableStreamType.swift @@ -94,11 +94,11 @@ public protocol PipeEmitTarget { public extension GWritableStreamType { @discardableResult - public func write(_ chunk: [ WriteType ], done: DoneCB? = nil) -> Bool { + func write(_ chunk: [ WriteType ], done: DoneCB? = nil) -> Bool { return writev(buckets: [ chunk ], done: done ) } - public func end(_ chunk: [ WriteType ]? = nil, doneWriting: DoneCB? = nil) { + func end(_ chunk: [ WriteType ]? = nil, doneWriting: DoneCB? = nil) { if let chunk = chunk { _ = writev(buckets: [ chunk ]) { if let cb = doneWriting { cb() } diff --git a/Sources/streams/ReadableByteStreamType.swift b/Sources/streams/ReadableByteStreamType.swift index e6bab7e..ba4ac32 100644 --- a/Sources/streams/ReadableByteStreamType.swift +++ b/Sources/streams/ReadableByteStreamType.swift @@ -42,11 +42,11 @@ public protocol ReadableByteStreamType : ReadableStreamType public extension GReadableStreamType where ReadType == UInt8 { // TODO: UTF8View should be a BucketType ... - public func push(_ chunk: String, done: DoneCB? = nil) { + func push(_ chunk: String, done: DoneCB? = nil) { let bucket = Array(chunk.utf8) // aaargh push(bucket) } - public func unshift(_ chunk: String, done: DoneCB? = nil) { + func unshift(_ chunk: String, done: DoneCB? = nil) { let bucket = Array(chunk.utf8) // aaargh unshift(bucket) } diff --git a/Sources/streams/SourceStream.swift b/Sources/streams/SourceStream.swift index 58157af..2e8988f 100644 --- a/Sources/streams/SourceStream.swift +++ b/Sources/streams/SourceStream.swift @@ -137,9 +137,7 @@ public class SourceStream public extension GReadableSourceType { - public func readable(hwm: Int = Self.defaultHighWaterMark) - -> SourceStream - { + func readable(hwm: Int = Self.defaultHighWaterMark) -> SourceStream { return SourceStream(source: self, highWaterMark: hwm) } diff --git a/Sources/streams/StreamPromise.swift b/Sources/streams/StreamPromise.swift index bfc445b..f32f7a9 100644 --- a/Sources/streams/StreamPromise.swift +++ b/Sources/streams/StreamPromise.swift @@ -23,13 +23,13 @@ public extension GReadableStreamType { } } - public func then(cb: @escaping () -> U) -> Promise { + func then(cb: @escaping () -> U) -> Promise { return promise.then(run: cb) } - public func then(cb: @escaping () -> Promise) -> Promise { + func then(cb: @escaping () -> Promise) -> Promise { return promise.then(run: cb) } - public func error(cb: @escaping ( Error ) -> Void) { + func error(cb: @escaping ( Error ) -> Void) { promise.error(run: cb) } } @@ -49,17 +49,17 @@ public extension GWritableStreamType { } } - public func then(cb: @escaping () -> U) -> Promise { + func then(cb: @escaping () -> U) -> Promise { return promise.then(run: cb) } - public func then(cb: @escaping () -> Promise) -> Promise { + func then(cb: @escaping () -> Promise) -> Promise { return promise.then(run: cb) } - public func error(cb: @escaping ( Error ) -> Void) { + func error(cb: @escaping ( Error ) -> Void) { promise.error(run: cb) } - public func then(cb: @escaping () -> S) + func then(cb: @escaping () -> S) -> Promise { return promise.then { () -> Promise in diff --git a/Sources/streams/TargetStream.swift b/Sources/streams/TargetStream.swift index 1329142..5e2f68e 100644 --- a/Sources/streams/TargetStream.swift +++ b/Sources/streams/TargetStream.swift @@ -70,9 +70,7 @@ open class TargetStream public extension GWritableTargetType { - public func writable(hwm v: Int = Self.defaultHighWaterMark) - -> TargetStream - { + func writable(hwm v: Int = Self.defaultHighWaterMark) -> TargetStream { return TargetStream(target: self, highWaterMark: v) } diff --git a/Sources/streams/WritableByteStreamType.swift b/Sources/streams/WritableByteStreamType.swift index fd53771..4d9df1f 100644 --- a/Sources/streams/WritableByteStreamType.swift +++ b/Sources/streams/WritableByteStreamType.swift @@ -35,12 +35,12 @@ public extension GWritableStreamType where WriteType == UInt8 { // TODO: UTF8View should be a BucketType ... @discardableResult - public func write(_ chunk: String, done: DoneCB? = nil) -> Bool { + func write(_ chunk: String, done: DoneCB? = nil) -> Bool { let bucket = Array(chunk.utf8) // aaargh return writev(buckets: [ bucket ], done: done) } - public func end(_ chunk: String, doneWriting: DoneCB? = nil) { + func end(_ chunk: String, doneWriting: DoneCB? = nil) { let bucket = Array(chunk.utf8) // aaargh _ = writev(buckets: [ bucket ]) { if let cb = doneWriting { cb() } diff --git a/Sources/streams/extra/TransformStream.swift b/Sources/streams/extra/TransformStream.swift index 1b4e18f..a054f66 100644 --- a/Sources/streams/extra/TransformStream.swift +++ b/Sources/streams/extra/TransformStream.swift @@ -134,7 +134,7 @@ open class TransformStream // MARK: - Readable (the OUTPUT!) override open func _primaryRead(count howMuchToRead: Int) { // #linux-public - log.enter(); defer { log.leave() } + log.enter() //fatalError("should not be called in transform streams") // => but it is called. @@ -145,6 +145,8 @@ open class TransformStream // is no 'on-demand' pulling of data (possible, because the write // part is push based too - if no one is writing to us, we can't // push to the readable). + + log.leave() } override open func read(count c: Int?) -> [ ReadType ]? { diff --git a/Sources/streams/pipes/Sequence2StreamPipe.swift b/Sources/streams/pipes/Sequence2StreamPipe.swift index aa9c4ba..c50321a 100644 --- a/Sources/streams/pipes/Sequence2StreamPipe.swift +++ b/Sources/streams/pipes/Sequence2StreamPipe.swift @@ -39,7 +39,7 @@ public extension Sequence { // TODO: We could support an async mode for blocking Sequences similar to // the GeneratorSource. - public func pipe + func pipe (_ outStream: TO, batchSize: Int = 10, endOnFinish: Bool = true) -> TO where Self.Iterator.Element == TO.WriteType diff --git a/Sources/streams/pipes/Stream2StreamPipe.swift b/Sources/streams/pipes/Stream2StreamPipe.swift index a673cc0..a3e07c4 100644 --- a/Sources/streams/pipes/Stream2StreamPipe.swift +++ b/Sources/streams/pipes/Stream2StreamPipe.swift @@ -56,7 +56,7 @@ public extension GReadableStreamType { /// - if the output stream is busy/full, the input stream is suspended /// @discardableResult - public func pipe + func pipe (_ outStream: TO, endOnFinish: Bool = true, passErrors: Bool = true) -> TO diff --git a/Sources/streams/strings/UTF8toCharacter.swift b/Sources/streams/strings/UTF8toCharacter.swift index 03d2e75..0602282 100644 --- a/Sources/streams/strings/UTF8toCharacter.swift +++ b/Sources/streams/strings/UTF8toCharacter.swift @@ -62,7 +62,11 @@ public class UTF8ToCharacter: TransformStream { { // This is still lame, but at least we don't spool up for plain ASCII if allData.isEmpty { - let idxOrNot = b.index(where: { ((highBit & $0) == highBit) }) + #if swift(>=5) + let idxOrNot = b.firstIndex(where: { ((highBit & $0) == highBit) }) + #else + let idxOrNot = b.index(where: { ((highBit & $0) == highBit) }) + #endif if let idx = idxOrNot { // found a high byte if idx > 0 { diff --git a/Sources/xsys/time.swift b/Sources/xsys/time.swift index 5747bbe..9bacfe8 100644 --- a/Sources/xsys/time.swift +++ b/Sources/xsys/time.swift @@ -38,25 +38,25 @@ public extension time_t { /// Returns the current time. - public static var now : time_t { return xsys.time(nil) } + static var now : time_t { return xsys.time(nil) } /// Initialize the `time_t` value from Unix `tm` value (date components). /// Assumes the values are given in *local time*. /// Remember that the `time_t` itself is in UTC. - public init(_ tm: xsys.struct_tm) { + init(_ tm: xsys.struct_tm) { self = tm.localTime } /// Initialize the `time_t` value from Unix `tm` value (date components). /// Assumes the values are given in *UTC time*. /// Remember that the `time_t` itself is in UTC. - public init(utc tm: xsys.struct_tm) { + init(utc tm: xsys.struct_tm) { self = tm.utcTime } /// Converts the `time_t` timestamp into date components (`tz` struct) living /// in the UTC timezone. /// Remember that the `time_t` itself is in UTC. - public var componentsInUTC : xsys.struct_tm { + var componentsInUTC : xsys.struct_tm { var t = self var tm = xsys.struct_tm() _ = xsys.gmtime_r(&t, &tm) @@ -66,7 +66,7 @@ public extension time_t { /// Converts the `time_t` timestamp into date components (`tz` struct) living /// in the local timezone of the Unix environment. /// Remember that the `time_t` itself is in UTC. - public var componentsInLocalTime : xsys.struct_tm { + var componentsInLocalTime : xsys.struct_tm { var t = self var tm = xsys.struct_tm() _ = xsys.localtime_r(&t, &tm) @@ -83,7 +83,7 @@ public extension time_t { /// /// xsys.time(nil).format("%a, %d %b %Y %H:%M:%S %Z") /// - public func format(_ sf: String) -> String { + func format(_ sf: String) -> String { return self.componentsInUTC.format(sf) } } @@ -94,21 +94,21 @@ public extension xsys.struct_tm { /// Create a Unix date components structure from a timestamp. This variant /// creates components in the local timezone. - public init(_ tm: time_t) { + init(_ tm: time_t) { self = tm.componentsInLocalTime } /// Create a Unix date components structure from a timestamp. This variant /// creates components in the UTC timezone. - public init(utc tm: time_t) { + init(utc tm: time_t) { self = tm.componentsInUTC } - public var utcTime : time_t { + var utcTime : time_t { var tm = self return timegm(&tm) } - public var localTime : time_t { + var localTime : time_t { var tm = self return mktime(&tm) } @@ -116,7 +116,7 @@ public extension xsys.struct_tm { /// Example `strftime` format (`man strftime`): /// "%a, %d %b %Y %H:%M:%S GMT" /// - public func format(_ sf: String, defaultCapacity: Int = 100) -> String { + func format(_ sf: String, defaultCapacity: Int = 100) -> String { var tm = self // Yes, yes, I know. diff --git a/Sources/xsys/timespec.swift b/Sources/xsys/timespec.swift index 6cc8f31..c2f81b5 100644 --- a/Sources/xsys/timespec.swift +++ b/Sources/xsys/timespec.swift @@ -30,7 +30,7 @@ public typealias timeval = Darwin.timeval public extension timespec { - public init(_ mts: mach_timespec_t) { + init(_ mts: mach_timespec_t) { #if swift(>=4.1) self.init() #endif @@ -38,7 +38,7 @@ public extension timespec { tv_nsec = Int(mts.tv_nsec) } - public static func monotonic() -> timespec { + static func monotonic() -> timespec { var cclock = clock_serv_t() var mts = mach_timespec_t() diff --git a/Sources/xsys/timeval_any.swift b/Sources/xsys/timeval_any.swift index c0f5e6e..1bf2fe0 100644 --- a/Sources/xsys/timeval_any.swift +++ b/Sources/xsys/timeval_any.swift @@ -44,10 +44,10 @@ public protocol timeval_any { public extension timeval_any { - public var componentsInUTC : xsys.struct_tm { + var componentsInUTC : xsys.struct_tm { return time_t(seconds).componentsInUTC } - public var componentsInLocalTime : xsys.struct_tm { + var componentsInLocalTime : xsys.struct_tm { return time_t(seconds).componentsInLocalTime } } diff --git a/xcconfig/Base.xcconfig b/xcconfig/Base.xcconfig index 06ccc52..2f7c8d1 100644 --- a/xcconfig/Base.xcconfig +++ b/xcconfig/Base.xcconfig @@ -59,4 +59,4 @@ LD_RUNPATH_SEARCH_PATHS = $(inherited) @executable_path/../Frameworks $(TOOLCHAI OTHER_SWIFT_FLAGS = -DXcode // This is a little lame (Xcode shouldn't tie the code to a version ..) -SWIFT_VERSION = 4.0 +SWIFT_VERSION = 5.0