mirror of
https://github.com/apple/swift-nio
synced 2026-11-26 04:57:49 +00:00
remove Foundation dependency
Motivation: Foundation is problematic for a few reasons: - its implementation is different on Linux and on macOS which means our macOS tests might be inaccurate - on macOS it uses ObjC Foundation which means the autorelease pool might get populated - it links the world on Linux which means we can't do static binaries at all Modifications: removed the last bits of Foundation dependency Result: no Foundation dependency
This commit is contained in:
1 parent
8e173fb348
commit
225951e7c3
16 files changed
+129
-18
No files matched your search
@@ -242,7 +242,9 @@ public struct ByteBuffer {
|
||||
public func dumpBytes(slice: Slice, offset: Int, length: Int) -> String {
|
||||
var desc = "["
|
||||
for i in Int(slice.lowerBound) + offset ..< Int(slice.lowerBound) + offset + length {
|
||||
desc += String(format: " %02x", self.bytes.advanced(by: Int(i)).assumingMemoryBound(to: UInt8.self).pointee)
|
||||
let byte = self.bytes.advanced(by: i).assumingMemoryBound(to: UInt8.self).pointee
|
||||
let hexByte = String(byte, radix: 16)
|
||||
desc += " \(hexByte.count == 1 ? " " : "")\(hexByte)"
|
||||
}
|
||||
desc += " ]"
|
||||
return desc
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
import NIO
|
||||
import class Foundation.NSNull // dummy for strings
|
||||
|
||||
private final class ChatHandler: ChannelInboundHandler {
|
||||
public typealias InboundIn = ByteBuffer
|
||||
|
||||
@@ -13,7 +13,6 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
import NIO
|
||||
import Dispatch
|
||||
import class Foundation.NSNull // dummy for strings
|
||||
|
||||
let newLine = "\n".utf8.first!
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
import NIO
|
||||
import class Foundation.NSNull // dummy for strings
|
||||
|
||||
print("Please enter line to send to the server")
|
||||
let line = readLine(strippingNewline: true)!
|
||||
@@ -45,7 +44,7 @@ private final class EchoHandler: ChannelInboundHandler {
|
||||
print("Client connected to \(ctx.channel.remoteAddress!)")
|
||||
|
||||
// We are connected its time to send the message to the server to initialize the ping-pong sequence.
|
||||
var buffer = ctx.channel.allocator.buffer(capacity: line.lengthOfBytes(using: String.Encoding.utf8))
|
||||
var buffer = ctx.channel.allocator.buffer(capacity: line.utf8.count)
|
||||
buffer.write(string: line)
|
||||
self.numBytes = buffer.readableBytes
|
||||
ctx.writeAndFlush(self.wrapOutboundOut(buffer), promise: nil)
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
import NIO
|
||||
import class Foundation.NSNull // dummy for strings
|
||||
|
||||
private final class EchoHandler: ChannelInboundHandler {
|
||||
public typealias InboundIn = ByteBuffer
|
||||
|
||||
+15
@@ -12,8 +12,23 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import NIO
|
||||
import struct Foundation.Data
|
||||
|
||||
/*
|
||||
* This is NIO's `NIOFoundationCompat` module which at the moment only adds `ByteBuffer` utility methods
|
||||
* for Foundation's `Data` type.
|
||||
*
|
||||
* The reason that it's not in the `NIO` module is that we don't want to have any direct Foundation dependencies
|
||||
* in `NIO` as Foundation is problematic for a few reasons:
|
||||
*
|
||||
* - its implementation is different on Linux and on macOS which means our macOS tests might be inaccurate
|
||||
* - on macOS Foundation is mostly written in ObjC which means the autorelease pool might get populated
|
||||
* - `swift-corelibs-foundation` (the OSS Foundation used on Linux) links the world which will prevent anyone from
|
||||
* having static binaries. It can also cause problems in the choice of an SSL library as Foundation already brings
|
||||
* the platforms OpenSSL in which might cause problems.
|
||||
*/
|
||||
|
||||
extension Data: ContiguousCollection {
|
||||
public func withUnsafeBytes<R>(_ fn: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
||||
return try self.withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> R in
|
||||
@@ -15,6 +15,19 @@
|
||||
import CNIOZlib
|
||||
import NIO
|
||||
|
||||
internal extension String {
|
||||
/// Test if this `Collection` starts with the unicode scalars of `needle`.
|
||||
///
|
||||
/// - note: This will be faster than `String.startsWith` as no unicode normalisations are performed.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - needle: The `Collection` of `Unicode.Scalar`s to match at the beginning of `self`
|
||||
/// - returns: If `self` started with the elements contained in `needle`.
|
||||
func startsWithSameUnicodeScalars<S: StringProtocol>(string needle: S) -> Bool {
|
||||
return self.unicodeScalars.starts(with: needle.unicodeScalars)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Given a header value, extracts the q value if there is one present. If one is not present,
|
||||
/// returns the default q value, 1.0.
|
||||
@@ -154,11 +167,11 @@ public final class HTTPResponseCompressor: ChannelInboundHandler, ChannelOutboun
|
||||
var anyQValue: Float = -1
|
||||
|
||||
for acceptHeader in acceptHeaders {
|
||||
if acceptHeader.hasPrefix("gzip") || acceptHeader.hasPrefix("x-gzip") {
|
||||
if acceptHeader.startsWithSameUnicodeScalars(string: "gzip") || acceptHeader.startsWithSameUnicodeScalars(string: "x-gzip") {
|
||||
gzipQValue = qValueFromHeader(acceptHeader)
|
||||
} else if acceptHeader.hasPrefix("deflate") {
|
||||
} else if acceptHeader.startsWithSameUnicodeScalars(string: "deflate") {
|
||||
deflateQValue = qValueFromHeader(acceptHeader)
|
||||
} else if acceptHeader.hasPrefix("*") {
|
||||
} else if acceptHeader.startsWithSameUnicodeScalars(string: "*") {
|
||||
anyQValue = qValueFromHeader(acceptHeader)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,16 +13,24 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
import NIO
|
||||
import NIOHTTP1
|
||||
import class Foundation.NSNull /* dummy just to get Foundation to link */
|
||||
|
||||
extension String {
|
||||
func chopPrefix(_ prefix: String) -> String? {
|
||||
if self.hasPrefix(prefix) {
|
||||
if self.unicodeScalars.starts(with: prefix.unicodeScalars) {
|
||||
return String(self[self.index(self.startIndex, offsetBy: prefix.count)...])
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func containsDotDot() -> Bool {
|
||||
for idx in self.indices {
|
||||
if self[idx] == "." && idx < self.index(before: self.endIndex) && self[self.index(after: idx)] == "." {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
private final class HTTPHandler: ChannelInboundHandler {
|
||||
@@ -203,7 +211,7 @@ private final class HTTPHandler: ChannelInboundHandler {
|
||||
|
||||
switch request {
|
||||
case .head(let request):
|
||||
guard !request.uri.contains("..") else {
|
||||
guard !request.uri.containsDotDot() else {
|
||||
let response = HTTPResponseHead(version: request.version, status: .forbidden)
|
||||
ctx.write(self.wrapOutboundOut(.head(response)), promise: nil)
|
||||
ctx.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil)
|
||||
@@ -237,7 +245,7 @@ private final class HTTPHandler: ChannelInboundHandler {
|
||||
let response = HTTPResponseHead(version: request.version, status: .ok)
|
||||
ctx.write(self.wrapOutboundOut(.head(response)), promise: nil)
|
||||
var buffer = ctx.channel.allocator.buffer(capacity: 100)
|
||||
buffer.write(string: "fail: \(error.localizedDescription)")
|
||||
buffer.write(string: "fail: \(error)")
|
||||
ctx.write(self.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: nil)
|
||||
return ctx.writeAndFlush(self.wrapOutboundOut(.end(nil)))
|
||||
} else {
|
||||
@@ -274,7 +282,7 @@ private final class HTTPHandler: ChannelInboundHandler {
|
||||
return HTTPResponseHead(version: request.version, status: .internalServerError)
|
||||
}
|
||||
}()
|
||||
body.write(string: error.localizedDescription)
|
||||
body.write(string: "\(error)")
|
||||
body.write(staticString: "\r\n")
|
||||
ctx.write(self.wrapOutboundOut(.head(response)), promise: nil)
|
||||
ctx.write(self.wrapOutboundOut(.body(.byteBuffer(body))), promise: nil)
|
||||
@@ -299,7 +307,7 @@ private final class HTTPHandler: ChannelInboundHandler {
|
||||
case .head(let request):
|
||||
keepAlive = request.isKeepAlive
|
||||
|
||||
if request.uri.hasPrefix("/dynamic") {
|
||||
if request.uri.unicodeScalars.starts(with: "/dynamic".unicodeScalars) {
|
||||
self.handler = self.dynamicHandler(request: request)
|
||||
self.handler!(ctx, reqPart)
|
||||
return
|
||||
|
||||
@@ -43,6 +43,12 @@ extension HTTPResponseCompressorTest {
|
||||
("testOutOfRangeQValuePreventsChoice", testOutOfRangeQValuePreventsChoice),
|
||||
("testRemovingHandlerFailsPendingWrites", testRemovingHandlerFailsPendingWrites),
|
||||
("testDoesNotBufferWritesNoAlgorithm", testDoesNotBufferWritesNoAlgorithm),
|
||||
("testStartsWithSameUnicodeScalarsWorksOnEmptyStrings", testStartsWithSameUnicodeScalarsWorksOnEmptyStrings),
|
||||
("testStartsWithSameUnicodeScalarsWorksOnLongerNeedleFalse", testStartsWithSameUnicodeScalarsWorksOnLongerNeedleFalse),
|
||||
("testStartsWithSameUnicodeScalarsWorksOnSameStrings", testStartsWithSameUnicodeScalarsWorksOnSameStrings),
|
||||
("testStartsWithSameUnicodeScalarsWorksOnPrefix", testStartsWithSameUnicodeScalarsWorksOnPrefix),
|
||||
("testStartsWithSameUnicodeScalarsSaysNoForTheSameStringInDifferentNormalisations", testStartsWithSameUnicodeScalarsSaysNoForTheSameStringInDifferentNormalisations),
|
||||
("testStartsWithSaysYesForTheSameStringInDifferentNormalisations", testStartsWithSaysYesForTheSameStringInDifferentNormalisations),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
import XCTest
|
||||
import CNIOZlib
|
||||
@testable import NIO
|
||||
import NIOHTTP1
|
||||
@testable import NIOHTTP1
|
||||
|
||||
private class PromiseOrderer {
|
||||
private var promiseArray: Array<EventLoopPromise<Void>>
|
||||
@@ -533,4 +533,44 @@ class HTTPResponseCompressorTest: XCTestCase {
|
||||
channel.pipeline.removeHandlers()
|
||||
try writePromise.futureResult.wait()
|
||||
}
|
||||
|
||||
func testStartsWithSameUnicodeScalarsWorksOnEmptyStrings() throws {
|
||||
XCTAssertTrue("".startsWithSameUnicodeScalars(string: ""))
|
||||
}
|
||||
|
||||
func testStartsWithSameUnicodeScalarsWorksOnLongerNeedleFalse() throws {
|
||||
XCTAssertFalse("_".startsWithSameUnicodeScalars(string: "__"))
|
||||
}
|
||||
|
||||
func testStartsWithSameUnicodeScalarsWorksOnSameStrings() throws {
|
||||
XCTAssertTrue("beer".startsWithSameUnicodeScalars(string: "beer"))
|
||||
}
|
||||
|
||||
func testStartsWithSameUnicodeScalarsWorksOnPrefix() throws {
|
||||
XCTAssertTrue("beer is good".startsWithSameUnicodeScalars(string: "beer"))
|
||||
}
|
||||
|
||||
func testStartsWithSameUnicodeScalarsSaysNoForTheSameStringInDifferentNormalisations() throws {
|
||||
let nfcEncodedEAigu = "\u{e9}"
|
||||
let nfdEncodedEAigu = "\u{65}\u{301}"
|
||||
|
||||
XCTAssertEqual(nfcEncodedEAigu, nfdEncodedEAigu)
|
||||
XCTAssertTrue(nfcEncodedEAigu.startsWithSameUnicodeScalars(string: nfcEncodedEAigu))
|
||||
XCTAssertTrue(nfdEncodedEAigu.startsWithSameUnicodeScalars(string: nfdEncodedEAigu))
|
||||
// the both do _not_ start like the other
|
||||
XCTAssertFalse(nfcEncodedEAigu.startsWithSameUnicodeScalars(string: nfdEncodedEAigu))
|
||||
XCTAssertFalse(nfdEncodedEAigu.startsWithSameUnicodeScalars(string: nfcEncodedEAigu))
|
||||
}
|
||||
|
||||
func testStartsWithSaysYesForTheSameStringInDifferentNormalisations() throws {
|
||||
let nfcEncodedEAigu = "\u{e9}"
|
||||
let nfdEncodedEAigu = "\u{65}\u{301}"
|
||||
|
||||
XCTAssertEqual(nfcEncodedEAigu, nfdEncodedEAigu)
|
||||
XCTAssertTrue(nfcEncodedEAigu.starts(with: nfcEncodedEAigu))
|
||||
XCTAssertTrue(nfdEncodedEAigu.starts(with: nfdEncodedEAigu))
|
||||
// the both do start like the other as we do unicode normalisation
|
||||
XCTAssertTrue(nfcEncodedEAigu.starts(with: nfdEncodedEAigu))
|
||||
XCTAssertTrue(nfdEncodedEAigu.starts(with: nfcEncodedEAigu))
|
||||
}
|
||||
}
|
||||
@@ -13,8 +13,9 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import NIOConcurrencyHelpers
|
||||
import NIO
|
||||
import NIOConcurrencyHelpers
|
||||
import NIOFoundationCompat
|
||||
import Dispatch
|
||||
@testable import NIOHTTP1
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
import XCTest
|
||||
@testable import NIO
|
||||
import NIOFoundationCompat
|
||||
import NIOTLS
|
||||
|
||||
private let libressl227HelloNoSni = """
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
import struct Foundation.Data
|
||||
import XCTest
|
||||
@testable import NIO
|
||||
import NIOFoundationCompat
|
||||
|
||||
class ByteBufferTest: XCTestCase {
|
||||
private let allocator = ByteBufferAllocator()
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ my_path="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
|
||||
swift_version=${swift_version:-4.0.2}
|
||||
version=$(git describe --abbrev=0 --tags)
|
||||
modules=(SwiftNIO NIOHTTP1 NIOTLS)
|
||||
modules=(SwiftNIO NIOHTTP1 NIOTLS NIOFoundationCompat)
|
||||
|
||||
if [[ $CI == true ]]; then
|
||||
# CI setup, assume this is running in an ubuntu docker container:
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
#!/bin/bash
|
||||
|
||||
swift build
|
||||
bin_path=$(swift build --show-bin-path)
|
||||
@@ -0,0 +1,24 @@
|
||||
#!/bin/bash
|
||||
|
||||
source defines.sh
|
||||
|
||||
function check_does_not_link() {
|
||||
library="$1"
|
||||
binary="$1"
|
||||
|
||||
case "$(uname -s)" in
|
||||
Darwin)
|
||||
assert_equal "" "$(otool -L "$binary" | grep "/$library")"
|
||||
;;
|
||||
Linux)
|
||||
assert_equal "" "$($ldd "$binary" | grep "lib$library")"
|
||||
;;
|
||||
*)
|
||||
fail "unsupported OS $(uname -s)"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
for binary in NIOEchoServer NIOEchoClient NIOChatServer NIOChatClient NIOHTTP1Server; do
|
||||
check_does_not_link Foundation "$bin_path/$binary"
|
||||
done
|
||||
Reference in new issue
Block a user