Skip to content

Commit

Permalink
Change unsafeDownCast to as! (#2802)
Browse files Browse the repository at this point in the history
# Motivation

In Swift 5.10 the usage of `unsafeDownCast` can lead to a miss-compile which will result in bad runtime behaviour.

# Modification

This PR changes the `unsafeDownCast` to use a `as!` instead. This is safe and should result in the same performance when done with `ManagedBuffer` which is inlinable.

# Result

No more miss compiles in 5.10
  • Loading branch information
FranzBusch authored Jul 24, 2024
1 parent 4feff3c commit 6630cc6
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
5 changes: 4 additions & 1 deletion Sources/NIOConcurrencyHelpers/NIOLock.swift
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,10 @@ final class LockStorage<Value>: ManagedBuffer<Value, LockPrimitive> {
let buffer = Self.create(minimumCapacity: 1) { _ in
value
}
let storage = unsafeDowncast(buffer, to: Self.self)
// Intentionally using a force cast here to avoid a miss compiliation in 5.10.
// This is as fast as an unsafeDownCast since ManagedBuffer is inlined and the optimizer
// can eliminate the upcast/downcast pair
let storage = buffer as! Self

storage.withUnsafeMutablePointers { _, lockPtr in
LockOperations.create(lockPtr)
Expand Down
11 changes: 9 additions & 2 deletions Sources/NIOPosix/Pool.swift
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,11 @@ extension PooledBuffer {
}

// Here we set up our memory bindings.
let storage = unsafeDowncast(baseStorage, to: Self.self)

// Intentionally using a force cast here to avoid a miss compiliation in 5.10.
// This is as fast as an unsafeDownCast since ManagedBuffer is inlined and the optimizer
// can eliminate the upcast/downcast pair
let storage = baseStorage as! Self
storage.withUnsafeMutablePointers { headPointer, tailPointer in
UnsafeRawPointer(tailPointer + headPointer.pointee.iovectorOffset).bindMemory(
to: IOVector.self,
Expand Down Expand Up @@ -277,7 +281,10 @@ struct PooledMsgBuffer: PoolElement {
head
}

let storage = unsafeDowncast(baseStorage, to: Self.self)
// Intentionally using a force cast here to avoid a miss compiliation in 5.10.
// This is as fast as an unsafeDownCast since ManagedBuffer is inlined and the optimizer
// can eliminate the upcast/downcast pair
let storage = baseStorage as! Self
storage.withUnsafeMutablePointers { headPointer, tailPointer in
UnsafeRawPointer(tailPointer + headPointer.pointee.msgHdrsOffset).bindMemory(
to: MMsgHdr.self,
Expand Down

0 comments on commit 6630cc6

Please sign in to comment.