Skip to content

Commit 924a6e5

Browse files
committed
Avoid an extra heap allocation during backtracing
1 parent e0cdd7f commit 924a6e5

File tree

1 file changed

+4
-6
lines changed

1 file changed

+4
-6
lines changed

Sources/Testing/SourceAttribution/Backtrace.swift

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,8 @@ public struct Backtrace: Sendable {
6161
public static func current(maximumAddressCount addressCount: Int = 128) -> Self {
6262
// NOTE: the exact argument/return types for backtrace() vary across
6363
// platforms, hence the use of .init() when calling it below.
64-
let addresses = [UnsafeMutableRawPointer?](unsafeUninitializedCapacity: addressCount) { addresses, initializedCount in
64+
withUnsafeTemporaryAllocation(of: UnsafeMutableRawPointer?.self, capacity: addressCount) { addresses in
65+
var initializedCount = 0
6566
#if SWT_TARGET_OS_APPLE
6667
if #available(_backtraceAsyncAPI, *) {
6768
initializedCount = backtrace_async(addresses.baseAddress!, addresses.count, nil)
@@ -79,15 +80,12 @@ public struct Backtrace: Sendable {
7980
#elseif os(WASI)
8081
// SEE: https://github.com/WebAssembly/WASI/issues/159
8182
// SEE: https://github.com/swiftlang/swift/pull/31693
82-
initializedCount = 0
8383
#else
8484
#warning("Platform-specific implementation missing: backtraces unavailable")
85-
initializedCount = 0
8685
#endif
87-
}
8886

89-
return addresses.withUnsafeBufferPointer { addresses in
90-
addresses.withMemoryRebound(to: UnsafeRawPointer?.self) { addresses in
87+
let endIndex = addresses.index(addresses.startIndex, offsetBy: initializedCount)
88+
return addresses[..<endIndex].withMemoryRebound(to: UnsafeRawPointer?.self) { addresses in
9189
Self(addresses: addresses)
9290
}
9391
}

0 commit comments

Comments
 (0)