Skip to content

Commit

Permalink
run swift-format
Browse files Browse the repository at this point in the history
  • Loading branch information
adam-fowler committed Nov 27, 2024
1 parent b945994 commit 15d83f8
Show file tree
Hide file tree
Showing 15 changed files with 309 additions and 162 deletions.
65 changes: 40 additions & 25 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,32 +24,47 @@ let package = Package(
.package(url: "https://github.com/swift-server/swift-service-lifecycle", from: "2.0.0"),
],
targets: [
.target(name: "WSClient", dependencies: [
.byName(name: "WSCore"),
.product(name: "HTTPTypes", package: "swift-http-types"),
.product(name: "Logging", package: "swift-log"),
.product(name: "NIOCore", package: "swift-nio"),
.product(name: "NIOHTTPTypesHTTP1", package: "swift-nio-extras"),
.product(name: "NIOPosix", package: "swift-nio"),
.product(name: "NIOSSL", package: "swift-nio-ssl"),
.product(name: "NIOTransportServices", package: "swift-nio-transport-services"),
.product(name: "NIOWebSocket", package: "swift-nio"),
], swiftSettings: swiftSettings),
.target(name: "WSCore", dependencies: [
.product(name: "HTTPTypes", package: "swift-http-types"),
.product(name: "NIOCore", package: "swift-nio"),
.product(name: "NIOWebSocket", package: "swift-nio"),
.product(name: "ServiceLifecycle", package: "swift-service-lifecycle"),
], swiftSettings: swiftSettings),
.target(name: "WSCompression", dependencies: [
.byName(name: "WSCore"),
.product(name: "CompressNIO", package: "compress-nio"),
], swiftSettings: swiftSettings),
.target(
name: "WSClient",
dependencies: [
.byName(name: "WSCore"),
.product(name: "HTTPTypes", package: "swift-http-types"),
.product(name: "Logging", package: "swift-log"),
.product(name: "NIOCore", package: "swift-nio"),
.product(name: "NIOHTTPTypesHTTP1", package: "swift-nio-extras"),
.product(name: "NIOPosix", package: "swift-nio"),
.product(name: "NIOSSL", package: "swift-nio-ssl"),
.product(name: "NIOTransportServices", package: "swift-nio-transport-services"),
.product(name: "NIOWebSocket", package: "swift-nio"),
],
swiftSettings: swiftSettings
),
.target(
name: "WSCore",
dependencies: [
.product(name: "HTTPTypes", package: "swift-http-types"),
.product(name: "NIOCore", package: "swift-nio"),
.product(name: "NIOWebSocket", package: "swift-nio"),
.product(name: "ServiceLifecycle", package: "swift-service-lifecycle"),
],
swiftSettings: swiftSettings
),
.target(
name: "WSCompression",
dependencies: [
.byName(name: "WSCore"),
.product(name: "CompressNIO", package: "compress-nio"),
],
swiftSettings: swiftSettings
),

.testTarget(name: "WebSocketTests", dependencies: [
.byName(name: "WSClient"),
.byName(name: "WSCompression"),
]),
.testTarget(
name: "WebSocketTests",
dependencies: [
.byName(name: "WSClient"),
.byName(name: "WSCompression"),
]
),
],
swiftLanguageVersions: [.v5, .version("6")]
)
20 changes: 13 additions & 7 deletions Sources/WSClient/Client/ClientConnection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,12 @@
import Logging
import NIOCore
import NIOPosix
import NIOWebSocket

#if canImport(Network)
import Network
import NIOTransportServices
#endif
import NIOWebSocket

/// A generic client connection to a server.
///
Expand Down Expand Up @@ -104,7 +105,9 @@ public struct ClientConnection<ClientChannel: ClientConnectionChannel>: Sendable
bootstrap = tsBootstrap
} else {
#if os(iOS) || os(tvOS)
self.logger.warning("Running BSD sockets on iOS or tvOS is not recommended. Please use NIOTSEventLoopGroup, to run with the Network framework")
self.logger.warning(
"Running BSD sockets on iOS or tvOS is not recommended. Please use NIOTSEventLoopGroup, to run with the Network framework"
)
#endif
bootstrap = self.createSocketsBootstrap()
}
Expand All @@ -117,13 +120,15 @@ public struct ClientConnection<ClientChannel: ClientConnectionChannel>: Sendable
do {
switch address.value {
case .hostname(let host, let port):
result = try await bootstrap
result =
try await bootstrap
.connect(host: host, port: port) { channel in
clientChannel.setup(channel: channel, logger: self.logger)
}
self.logger.debug("Client connnected to \(host):\(port)")
case .unixDomainSocket(let path):
result = try await bootstrap
result =
try await bootstrap
.connect(unixDomainSocketPath: path) { channel in
clientChannel.setup(channel: channel, logger: self.logger)
}
Expand All @@ -137,15 +142,16 @@ public struct ClientConnection<ClientChannel: ClientConnectionChannel>: Sendable

/// create a BSD sockets based bootstrap
private func createSocketsBootstrap() -> ClientBootstrap {
return ClientBootstrap(group: self.eventLoopGroup)
ClientBootstrap(group: self.eventLoopGroup)
.channelOption(ChannelOptions.allowRemoteHalfClosure, value: true)
}

#if canImport(Network)
/// create a NIOTransportServices bootstrap using Network.framework
private func createTSBootstrap() -> NIOTSConnectionBootstrap? {
guard let bootstrap = NIOTSConnectionBootstrap(validatingGroup: self.eventLoopGroup)?
.channelOption(ChannelOptions.allowRemoteHalfClosure, value: true)
guard
let bootstrap = NIOTSConnectionBootstrap(validatingGroup: self.eventLoopGroup)?
.channelOption(ChannelOptions.allowRemoteHalfClosure, value: true)
else {
return nil
}
Expand Down
51 changes: 30 additions & 21 deletions Sources/WSClient/Client/Parser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,12 @@ struct Parser: Sendable {

/// Return contents of parser as a string
var count: Int {
return self.range.count
self.range.count
}

/// Return contents of parser as a string
var string: String {
return makeString(self.buffer[self.range])
makeString(self.buffer[self.range])
}

private var buffer: [UInt8]
Expand All @@ -74,12 +74,12 @@ extension Parser {
self.range = range

precondition(range.startIndex >= 0 && range.endIndex <= self.buffer.endIndex)
precondition(range.startIndex == self.buffer.endIndex || self.buffer[range.startIndex] & 0xC0 != 0x80) // check we arent in the middle of a UTF8 character
precondition(range.startIndex == self.buffer.endIndex || self.buffer[range.startIndex] & 0xC0 != 0x80) // check we arent in the middle of a UTF8 character
}

/// initialise a parser that parses a section of the buffer attached to this parser
func subParser(_ range: Range<Int>) -> Parser {
return Parser(self, range: range)
Parser(self, range: range)
}
}

Expand All @@ -99,7 +99,10 @@ extension Parser {
mutating func read(_ char: Unicode.Scalar) throws -> Bool {
let initialIndex = self.index
let c = try character()
guard c == char else { self.index = initialIndex; return false }
guard c == char else {
self.index = initialIndex
return false
}
return true
}

Expand All @@ -110,7 +113,10 @@ extension Parser {
mutating func read(_ characterSet: Set<Unicode.Scalar>) throws -> Bool {
let initialIndex = self.index
let c = try character()
guard characterSet.contains(c) else { self.index = initialIndex; return false }
guard characterSet.contains(c) else {
self.index = initialIndex
return false
}
return true
}

Expand All @@ -122,7 +128,10 @@ extension Parser {
let initialIndex = self.index
guard string.count > 0 else { throw Error.emptyString }
let subString = try read(count: string.count)
guard subString.string == string else { self.index = initialIndex; return false }
guard subString.string == string else {
self.index = initialIndex
return false
}
return true
}

Expand Down Expand Up @@ -273,7 +282,7 @@ extension Parser {
@discardableResult mutating func read(while: Unicode.Scalar) -> Int {
var count = 0
while !self.reachedEnd(),
unsafeCurrent() == `while`
unsafeCurrent() == `while`
{
unsafeAdvance()
count += 1
Expand All @@ -287,7 +296,7 @@ extension Parser {
@discardableResult mutating func read(while characterSet: Set<Unicode.Scalar>) -> Parser {
let startIndex = self.index
while !self.reachedEnd(),
characterSet.contains(unsafeCurrent())
characterSet.contains(unsafeCurrent())
{
unsafeAdvance()
}
Expand All @@ -300,7 +309,7 @@ extension Parser {
@discardableResult mutating func read(while: (Unicode.Scalar) -> Bool) -> Parser {
let startIndex = self.index
while !self.reachedEnd(),
`while`(unsafeCurrent())
`while`(unsafeCurrent())
{
unsafeAdvance()
}
Expand All @@ -313,7 +322,7 @@ extension Parser {
@discardableResult mutating func read(while keyPath: KeyPath<Unicode.Scalar, Bool>) -> Parser {
let startIndex = self.index
while !self.reachedEnd(),
unsafeCurrent()[keyPath: keyPath]
unsafeCurrent()[keyPath: keyPath]
{
unsafeAdvance()
}
Expand Down Expand Up @@ -342,7 +351,7 @@ extension Parser {
/// Return whether we have reached the end of the buffer
/// - Returns: Have we reached the end
func reachedEnd() -> Bool {
return self.index == self.range.endIndex
self.index == self.range.endIndex
}
}

Expand Down Expand Up @@ -422,7 +431,7 @@ extension Parser: Sequence {
public typealias Element = Unicode.Scalar

public func makeIterator() -> Iterator {
return Iterator(self)
Iterator(self)
}

public struct Iterator: IteratorProtocol {
Expand All @@ -442,22 +451,22 @@ extension Parser: Sequence {
}

// internal versions without checks
private extension Parser {
func unsafeCurrent() -> Unicode.Scalar {
return decodeUTF8Character(at: self.index).0
extension Parser {
fileprivate func unsafeCurrent() -> Unicode.Scalar {
decodeUTF8Character(at: self.index).0
}

mutating func unsafeCurrentAndAdvance() -> Unicode.Scalar {
fileprivate mutating func unsafeCurrentAndAdvance() -> Unicode.Scalar {
let (unicodeScalar, index) = decodeUTF8Character(at: self.index)
self.index = index
return unicodeScalar
}

mutating func _setPosition(_ index: Int) {
fileprivate mutating func _setPosition(_ index: Int) {
self.index = index
}

func makeString<Bytes: Collection>(_ bytes: Bytes) -> String where Bytes.Element == UInt8, Bytes.Index == Int {
fileprivate func makeString<Bytes: Collection>(_ bytes: Bytes) -> String where Bytes.Element == UInt8, Bytes.Index == Int {
if let string = bytes.withContiguousStorageIfAvailable({ String(decoding: $0, as: Unicode.UTF8.self) }) {
return string
} else {
Expand Down Expand Up @@ -624,7 +633,7 @@ extension Parser {
do {
if #available(macOS 11, macCatalyst 14.0, iOS 14.0, tvOS 14.0, *) {
return try String(unsafeUninitializedCapacity: range.endIndex - index) { bytes -> Int in
return try _percentDecode(self.buffer[self.index..<range.endIndex], bytes)
try _percentDecode(self.buffer[self.index..<range.endIndex], bytes)
}
} else {
let newBuffer = try [UInt8](unsafeUninitializedCapacity: self.range.endIndex - self.index) { bytes, count in
Expand All @@ -640,7 +649,7 @@ extension Parser {

extension Unicode.Scalar {
var isWhitespace: Bool {
return properties.isWhitespace
properties.isWhitespace
}

var isNewline: Bool {
Expand Down
13 changes: 8 additions & 5 deletions Sources/WSClient/Client/TSTLSOptions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public struct TSTLSOptions: Sendable {
let secIdentity: SecIdentity

public static func secIdentity(_ secIdentity: SecIdentity) -> Self {
return .init(secIdentity: secIdentity)
.init(secIdentity: secIdentity)
}

public static func p12(filename: String, password: String) throws -> Self {
Expand Down Expand Up @@ -101,7 +101,7 @@ public struct TSTLSOptions: Sendable {

/// TSTLSOptions holding options
public static func options(_ options: NWProtocolTLS.Options) -> Self {
return .init(value: .some(options))
.init(value: .some(options))
}

public static func options(
Expand All @@ -117,7 +117,9 @@ public struct TSTLSOptions: Sendable {
}

public static func options(
clientIdentity: Identity, trustRoots: Certificates = .none, serverName: String? = nil
clientIdentity: Identity,
trustRoots: Certificates = .none,
serverName: String? = nil
) -> Self? {
let options = NWProtocolTLS.Options()

Expand All @@ -143,15 +145,16 @@ public struct TSTLSOptions: Sendable {
}
sec_protocol_verify_complete(result)
}
}, Self.tlsDispatchQueue
},
Self.tlsDispatchQueue
)
}
return .init(value: .some(options))
}

/// Empty TSTLSOptions
public static var none: Self {
return .init(value: .none)
.init(value: .none)
}

var options: NWProtocolTLS.Options? {
Expand Down
24 changes: 12 additions & 12 deletions Sources/WSClient/Client/URI.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,27 +21,27 @@ struct URI: Sendable, CustomStringConvertible, ExpressibleByStringLiteral {
self.rawValue = rawValue
}

static var http: Self { return .init(rawValue: "http") }
static var https: Self { return .init(rawValue: "https") }
static var unix: Self { return .init(rawValue: "unix") }
static var http_unix: Self { return .init(rawValue: "http_unix") }
static var https_unix: Self { return .init(rawValue: "https_unix") }
static var ws: Self { return .init(rawValue: "ws") }
static var wss: Self { return .init(rawValue: "wss") }
static var http: Self { .init(rawValue: "http") }
static var https: Self { .init(rawValue: "https") }
static var unix: Self { .init(rawValue: "unix") }
static var http_unix: Self { .init(rawValue: "http_unix") }
static var https_unix: Self { .init(rawValue: "https_unix") }
static var ws: Self { .init(rawValue: "ws") }
static var wss: Self { .init(rawValue: "wss") }
}

let string: String

/// URL scheme
var scheme: Scheme? { return self._scheme.map { .init(rawValue: $0.string) } }
var scheme: Scheme? { self._scheme.map { .init(rawValue: $0.string) } }
/// URL host
var host: String? { return self._host.map(\.string) }
var host: String? { self._host.map(\.string) }
/// URL port
var port: Int? { return self._port.map { Int($0.string) } ?? nil }
var port: Int? { self._port.map { Int($0.string) } ?? nil }
/// URL path
var path: String { return self._path.map(\.string) ?? "/" }
var path: String { self._path.map(\.string) ?? "/" }
/// URL query
var query: String? { return self._query.map { String($0.string) }}
var query: String? { self._query.map { String($0.string) } }

private let _scheme: Parser?
private let _host: Parser?
Expand Down
Loading

0 comments on commit 15d83f8

Please sign in to comment.