Skip to content

Commit

Permalink
where possible, use uninitialized [UInt8] buffers
Browse files Browse the repository at this point in the history
  • Loading branch information
lhoward committed Nov 13, 2024
1 parent 5297b35 commit 0d7273f
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 7 deletions.
2 changes: 1 addition & 1 deletion Package.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// swift-tools-version: 5.8
// swift-tools-version: 5.9

import Foundation
import PackageDescription
Expand Down
14 changes: 11 additions & 3 deletions Sources/IORing/IORing.swift
Original file line number Diff line number Diff line change
Expand Up @@ -545,7 +545,7 @@ private extension IORing {
count: Int,
link: Bool = false
) throws -> AsyncThrowingChannel<[UInt8], Error> {
var buffer = [UInt8](repeating: 0, count: count)
var buffer = [UInt8]._unsafelyInitialized(count: count)
return try prepareAndSubmitMultishot(
.recv,
fd: fd,
Expand Down Expand Up @@ -695,7 +695,7 @@ public extension IORing {
}

func read(count: Int, from fd: FileDescriptorRepresentable) async throws -> [UInt8] {
var buffer = [UInt8](repeating: 0, count: count)
var buffer = [UInt8]._unsafelyInitialized(count: count)
let nread = try await read(into: &buffer, count: count, from: fd)
return Array(buffer.prefix(nread))
}
Expand All @@ -722,7 +722,7 @@ public extension IORing {
}

func receive(count: Int, from fd: FileDescriptorRepresentable) async throws -> [UInt8] {
var buffer = [UInt8](repeating: 0, count: count)
var buffer = [UInt8]._unsafelyInitialized(count: count)
try await io_uring_op_recv(fd: fd, buffer: &buffer)
return buffer
}
Expand Down Expand Up @@ -958,3 +958,11 @@ extension IORing: Hashable {
ObjectIdentifier(self).hash(into: &hasher)
}
}

package extension [UInt8] {
static func _unsafelyInitialized(count: Int) -> Self {
Self(unsafeUninitializedCapacity: count) { _, initializedCount in
initializedCount = count
}
}
}
8 changes: 5 additions & 3 deletions Sources/IORingUtils/Extensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,12 @@ extension Message: CustomStringConvertible {
buffer: [UInt8],
flags: UInt32 = 0
) throws {
var addressBuffer = [UInt8](repeating: 0, count: Int(address.size))
addressBuffer.withUnsafeMutableBytes { bytes in
let addressSize = Int(address.size)
let addressBuffer = [UInt8](unsafeUninitializedCapacity: Int(address.size)) { buffer,
initializedCount in
var storage = address.asStorage()
_ = memcpy(bytes.baseAddress!, &storage, bytes.count)
_ = memcpy(buffer.baseAddress!, &storage, addressSize)
initializedCount = addressSize
}
try self.init(name: addressBuffer, buffer: buffer, flags: flags)
}
Expand Down

0 comments on commit 0d7273f

Please sign in to comment.