From 69744b4898f6af02e3283cc03bf8fda7d75b2bb9 Mon Sep 17 00:00:00 2001 From: Johannes Weiss Date: Wed, 1 Aug 2018 18:51:33 +0100 Subject: [PATCH] switch Socket API to Unsafe(Mutable)RawBufferPointers (#540) Motivation: The (`internal`) `Socket` API should've always been based on `Unsafe(Mutable)RawBufferPointer`s but for some reason (probably just age) it was `Unsafe(Mutable)Pointer` alongside a `size: Int`. Modifications: switched the `Socket` APIs from `Unsafe(Mutable)Pointer` and a size to `Unsafe(Mutable)RawBufferPointer`. Result: better Swift code. Motivation: Explain here the context, and why you're making that change. What is the problem you're trying to solve. Modifications: Describe the modifications you've done. Result: After your change, what will change. --- Sources/NIO/Socket.swift | 33 ++++++++++++----------- Sources/NIO/SocketChannel.swift | 17 +++++++----- Tests/NIOTests/ChannelTests.swift | 10 +++---- Tests/NIOTests/DatagramChannelTests.swift | 2 +- 4 files changed, 33 insertions(+), 29 deletions(-) diff --git a/Sources/NIO/Socket.swift b/Sources/NIO/Socket.swift index 95c33c2e4..7b01407c9 100644 --- a/Sources/NIO/Socket.swift +++ b/Sources/NIO/Socket.swift @@ -104,13 +104,12 @@ public typealias IOVector = iovec /// Write data to the remote peer. /// /// - parameters: - /// - pointer: The data to write. - /// - size: The number of bytes to write. + /// - pointer: Pointer (and size) to data to write. /// - returns: The `IOResult` which indicates how much data could be written and if the operation returned before all could be written (because the socket is in non-blocking mode). /// - throws: An `IOError` if the operation failed. - func write(pointer: UnsafePointer, size: Int) throws -> IOResult { + func write(pointer: UnsafeRawBufferPointer) throws -> IOResult { return try withUnsafeFileDescriptor { fd in - try Posix.write(descriptor: fd, pointer: pointer, size: size) + try Posix.write(descriptor: fd, pointer: pointer.baseAddress!, size: pointer.count) } } @@ -129,43 +128,45 @@ public typealias IOVector = iovec /// Send data to a destination. /// /// - parameters: - /// - pointer: The data to send. - /// - size: The number of bytes to send. + /// - pointer: Pointer (and size) to the data to send. /// - destinationPtr: The destination to which the data should be sent. /// - returns: The `IOResult` which indicates how much data could be written and if the operation returned before all could be written (because the socket is in non-blocking mode). /// - throws: An `IOError` if the operation failed. - func sendto(pointer: UnsafePointer, size: Int, destinationPtr: UnsafePointer, destinationSize: socklen_t) throws -> IOResult { + func sendto(pointer: UnsafeRawBufferPointer, destinationPtr: UnsafePointer, destinationSize: socklen_t) throws -> IOResult { return try withUnsafeFileDescriptor { fd in - try Posix.sendto(descriptor: fd, pointer: UnsafeMutablePointer(mutating: pointer), size: size, destinationPtr: destinationPtr, destinationSize: destinationSize) + try Posix.sendto(descriptor: fd, pointer: UnsafeMutableRawPointer(mutating: pointer.baseAddress!), + size: pointer.count, destinationPtr: destinationPtr, + destinationSize: destinationSize) } } /// Read data from the socket. /// /// - parameters: - /// - pointer: The pointer to the storage into which the data should be read. - /// - size: The (max) number of bytes to read. + /// - pointer: The pointer (and size) to the storage into which the data should be read. /// - returns: The `IOResult` which indicates how much data could be read and if the operation returned before all could be read (because the socket is in non-blocking mode). /// - throws: An `IOError` if the operation failed. - func read(pointer: UnsafeMutablePointer, size: Int) throws -> IOResult { + func read(pointer: UnsafeMutableRawBufferPointer) throws -> IOResult { return try withUnsafeFileDescriptor { fd in - try Posix.read(descriptor: fd, pointer: pointer, size: size) + try Posix.read(descriptor: fd, pointer: pointer.baseAddress!, size: pointer.count) } } /// Receive data from the socket. /// /// - parameters: - /// - pointer: The pointer to the storage into which the data should be read. - /// - size: The (max) number of bytes to read. + /// - pointer: The pointer (and size) to the storage into which the data should be read. /// - storage: The address from which the data was received /// - storageLen: The size of the storage itself. /// - returns: The `IOResult` which indicates how much data could be received and if the operation returned before all could be received (because the socket is in non-blocking mode). /// - throws: An `IOError` if the operation failed. - func recvfrom(pointer: UnsafeMutablePointer, size: Int, storage: inout sockaddr_storage, storageLen: inout socklen_t) throws -> IOResult<(Int)> { + func recvfrom(pointer: UnsafeMutableRawBufferPointer, storage: inout sockaddr_storage, storageLen: inout socklen_t) throws -> IOResult<(Int)> { return try withUnsafeFileDescriptor { fd in try storage.withMutableSockAddr { (storagePtr, _) in - try Posix.recvfrom(descriptor: fd, pointer: pointer, len: size, addr: storagePtr, addrlen: &storageLen) + try Posix.recvfrom(descriptor: fd, pointer: pointer.baseAddress!, + len: pointer.count, + addr: storagePtr, + addrlen: &storageLen) } } } diff --git a/Sources/NIO/SocketChannel.swift b/Sources/NIO/SocketChannel.swift index ccb3faeb8..fdb2229ea 100644 --- a/Sources/NIO/SocketChannel.swift +++ b/Sources/NIO/SocketChannel.swift @@ -13,10 +13,10 @@ //===----------------------------------------------------------------------===// private extension ByteBuffer { - mutating func withMutableWritePointer(body: (UnsafeMutablePointer, Int) throws -> IOResult) rethrows -> IOResult { + mutating func withMutableWritePointer(body: (UnsafeMutableRawBufferPointer) throws -> IOResult) rethrows -> IOResult { var singleResult: IOResult! _ = try self.writeWithUnsafeMutableBytes { ptr in - let localWriteResult = try body(ptr.baseAddress!.assumingMemoryBound(to: UInt8.self), ptr.count) + let localWriteResult = try body(ptr) singleResult = localWriteResult switch localWriteResult { case .processed(let written): @@ -133,7 +133,7 @@ final class SocketChannel: BaseSocketChannel { // Reset reader and writerIndex and so allow to have the buffer filled again. This is better here than at // the end of the loop to not do an allocation when the loop exits. buffer.clear() - switch try buffer.withMutableWritePointer(body: self.socket.read(pointer:size:)) { + switch try buffer.withMutableWritePointer(body: self.socket.read(pointer:)) { case .processed(let bytesRead): if bytesRead > 0 { let mayGrow = recvAllocator.record(actualReadBytes: bytesRead) @@ -180,7 +180,7 @@ final class SocketChannel: BaseSocketChannel { return .processed(0) } // normal write - return try self.socket.write(pointer: ptr.baseAddress!.assumingMemoryBound(to: UInt8.self), size: ptr.count) + return try self.socket.write(pointer: ptr) }, vectorBufferWriteOperation: { ptrs in // Gathering write try self.socket.writev(iovecs: ptrs) @@ -604,7 +604,9 @@ final class DatagramChannel: BaseSocketChannel { } buffer.clear() - let result = try buffer.withMutableWritePointer { try self.socket.recvfrom(pointer: $0, size: $1, storage: &rawAddress, storageLen: &rawAddressLength) } + let result = try buffer.withMutableWritePointer { + try self.socket.recvfrom(pointer: $0, storage: &rawAddress, storageLen: &rawAddressLength) + } switch result { case .processed(let bytesRead): assert(bytesRead > 0) @@ -677,8 +679,9 @@ final class DatagramChannel: BaseSocketChannel { return .processed(0) } // normal write - return try self.socket.sendto(pointer: ptr.baseAddress!.assumingMemoryBound(to: UInt8.self), size: ptr.count, - destinationPtr: destinationPtr, destinationSize: destinationSize) + return try self.socket.sendto(pointer: ptr, + destinationPtr: destinationPtr, + destinationSize: destinationSize) }, vectorWriteOperation: { msgs in try self.socket.sendmmsg(msgs: msgs) }) diff --git a/Tests/NIOTests/ChannelTests.swift b/Tests/NIOTests/ChannelTests.swift index 46d15825c..2439d4be3 100644 --- a/Tests/NIOTests/ChannelTests.swift +++ b/Tests/NIOTests/ChannelTests.swift @@ -1151,7 +1151,7 @@ public class ChannelTests: XCTestCase { XCTAssertEqual(ChannelError.outputClosed, err) } let written = try buffer.withUnsafeReadableBytes { p in - try accepted.write(pointer: p.baseAddress!.assumingMemoryBound(to: UInt8.self), size: 4) + try accepted.write(pointer: UnsafeRawBufferPointer(start: p.baseAddress, count: 4)) } if case .processed(let numBytes) = written { XCTAssertEqual(4, numBytes) @@ -1209,7 +1209,7 @@ public class ChannelTests: XCTestCase { buffer.write(string: "1234") let written = try buffer.withUnsafeReadableBytes { p in - try accepted.write(pointer: p.baseAddress!.assumingMemoryBound(to: UInt8.self), size: 4) + try accepted.write(pointer: UnsafeRawBufferPointer(start: p.baseAddress, count: 4)) } switch written { @@ -2042,16 +2042,16 @@ public class ChannelTests: XCTestCase { init(protocolFamily: CInt) throws { try super.init(protocolFamily: protocolFamily, type: Posix.SOCK_STREAM, setNonBlocking: true) } - override func read(pointer: UnsafeMutablePointer, size: Int) throws -> IOResult { + override func read(pointer: UnsafeMutableRawBufferPointer) throws -> IOResult { defer { self.firstReadHappened = true } - XCTAssertGreaterThan(size, 0) + XCTAssertGreaterThan(pointer.count, 0) if self.firstReadHappened { // this is a copy of the exact error that'd come out of the real Socket.read throw IOError.init(errnoCode: ECONNRESET, function: "read(descriptor:pointer:size:)") } else { - pointer.pointee = 0xff + pointer[0] = 0xff return .processed(1) } } diff --git a/Tests/NIOTests/DatagramChannelTests.swift b/Tests/NIOTests/DatagramChannelTests.swift index 8961c1d45..8726b92ad 100644 --- a/Tests/NIOTests/DatagramChannelTests.swift +++ b/Tests/NIOTests/DatagramChannelTests.swift @@ -392,7 +392,7 @@ final class DatagramChannelTests: XCTestCase { try super.init(protocolFamily: AF_INET, type: Posix.SOCK_DGRAM) } - override func recvfrom(pointer: UnsafeMutablePointer, size: Int, storage: inout sockaddr_storage, storageLen: inout socklen_t) throws -> IOResult<(Int)> { + override func recvfrom(pointer: UnsafeMutableRawBufferPointer, storage: inout sockaddr_storage, storageLen: inout socklen_t) throws -> IOResult<(Int)> { if let err = self.error { self.error = nil throw IOError(errnoCode: err, function: "recvfrom")