diff --git a/Package.swift b/Package.swift index ff28c3ea..cc59123f 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:6.2 +// swift-tools-version:6.4 //===----------------------------------------------------------------------===// // // This source file is part of the Swift Collections open source project @@ -341,6 +341,7 @@ let targets: [CustomTarget] = [ .target( kind: .exported, name: "TrailingElementsModule", + dependencies: ["InternalCollectionsUtilities"], exclude: ["CMakeLists.txt"]), .target( kind: .test, diff --git a/Package@swift-6.2.swift b/Package@swift-6.2.swift new file mode 100644 index 00000000..8941cbbf --- /dev/null +++ b/Package@swift-6.2.swift @@ -0,0 +1,390 @@ +// swift-tools-version:6.2 +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception +// +//===----------------------------------------------------------------------===// + +import PackageDescription + +let _traits: Set = [ + .default( + enabledTraits: [ +// "UnstableContainersPreview", +// "UnstableHashedContainers", +// "UnstableSortedCollections", + ]), + .trait( + name: "UnstableContainersPreview", + description: """ + Enables source-unstable components of the ContainersPreview module in + swift-collections. This allows experimental use of the Container + protocols and associated algorithms. + """), + .trait( + name: "UnstableSortedCollections", + description: """ + Enables source-unstable prototypes of `SortedSet` and `SortedDictionary`, + two potential new collection types implementing in-memory B-trees. + These are early developer drafts, and they not ready for use in + production. We will make significant, source breaking API changes to these + types before they ship. + """), + .trait( + name: "UnstableHashedContainers", + description: """ + Enables support for noncopyable set members and dictionary keys in + `BasicContainers`. This requires a Standard Library with generalized + `Equatable` and `Hashable` protocols that allow noncopyable conformers; + this feature has not shipped in a stable compiler version yet. + """), +] + +// This package recognizes the conditional compilation flags listed below. +// To use enable them, uncomment the corresponding lines or define them +// from the package manager command line: +// +// swift build -Xswiftc -DCOLLECTIONS_INTERNAL_CHECKS +var defines: [SwiftSetting] = [ + // Enables internal consistency checks at the end of initializers and + // mutating operations. This can have very significant overhead, so enabling + // this setting invalidates all documented performance guarantees. + // + // This is mostly useful while debugging an issue with the implementation of + // the hash table itself. This setting should never be enabled in production + // code. +// .define("COLLECTIONS_INTERNAL_CHECKS"), + + // Hashing collections provided by this package usually seed their hash + // function with the address of the memory location of their storage, + // to prevent some common hash table merge/copy operations from regressing to + // quadratic behavior. This setting turns off this mechanism, seeding + // the hash function with the table's size instead. + // + // When used in conjunction with the SWIFT_DETERMINISTIC_HASHING environment + // variable, this enables reproducible hashing behavior. + // + // This is mostly useful while debugging an issue with the implementation of + // the hash table itself. This setting should never be enabled in production + // code. +// .define("COLLECTIONS_DETERMINISTIC_HASHING"), + + // Enables randomized testing of some data structure implementations. + .define("COLLECTIONS_RANDOMIZED_TESTING"), + + // Enable this to build the sources as a single, large module. + // This removes the distinct modules for each data structure, instead + // putting them all directly into the `Collections` module. + // Note: This is a source-incompatible variation of the default configuration. +// .define("COLLECTIONS_SINGLE_MODULE"), + + // Enables longer, more exhaustive tests. +// .define("COLLECTIONS_LONG_TESTS"), +] + +let availabilityMacros: KeyValuePairs = [ + "SwiftStdlib 5.0": "macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2", + "SwiftStdlib 5.1": "macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0", + "SwiftStdlib 5.6": "macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4", + "SwiftStdlib 5.7": "macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0", + "SwiftStdlib 5.8": "macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4", + "SwiftStdlib 5.9": "macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0", + "SwiftStdlib 5.10": "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4, visionOS 1.1", + "SwiftStdlib 6.0": "macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0", + "SwiftStdlib 6.1": "macOS 15.4, iOS 18.4, watchOS 11.4, tvOS 18.4, visionOS 2.4", + "SwiftStdlib 6.2": "macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, visionOS 26.0", + "SwiftStdlib 6.3": "macOS 26.4, iOS 26.4, watchOS 26.4, tvOS 26.4, visionOS 26.4", + "SwiftStdlib 6.4": "macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0", + "SwiftStdlib 6.5": "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999", + // Note: if you touch these, please make sure to also update the similar lists in + // CMakeLists.txt and Xcode/Shared.xcconfig. +] + +let extraSettings: [SwiftSetting] = [ + //.strictMemorySafety(), + .enableUpcomingFeature("MemberImportVisibility"), + .enableExperimentalFeature("BuiltinModule"), + .enableExperimentalFeature("Lifetimes"), + .enableExperimentalFeature("InoutLifetimeDependence"), + .enableExperimentalFeature("AddressableParameters"), + .enableExperimentalFeature("AddressableTypes"), + .enableExperimentalFeature("SuppressedAssociatedTypesWithDefaults"), // Requires Swift 6.4 + .enableExperimentalFeature("BorrowingSequence"), // 6.4 + // Note: if you touch these, please make sure to also update the similar lists in + // CMakeLists.txt and Xcode/Shared.xcconfig. +] + +let _baseSettings: [SwiftSetting] = ( + defines + + availabilityMacros.map { name, value in + .enableExperimentalFeature("AvailabilityMacro=\(name): \(value)") + } +) + +let _settings: [SwiftSetting] = _baseSettings + extraSettings +let _testSettings: [SwiftSetting] = _settings + +struct CustomTarget { + enum Kind { + case exported + case hidden + case test + case testSupport + } + + var kind: Kind + var name: String + var dependencies: [Target.Dependency] + var directory: String + var exclude: [String] + var sources: [String]? + var settings: [SwiftSetting] +} + +extension CustomTarget.Kind { + func path(for name: String) -> String { + switch self { + case .exported, .hidden: return "Sources/\(name)" + case .test, .testSupport: return "Tests/\(name)" + } + } + + var isTest: Bool { + switch self { + case .exported, .hidden: return false + case .test, .testSupport: return true + } + } +} + +extension CustomTarget { + static func target( + kind: Kind, + name: String, + dependencies: [Target.Dependency] = [], + directory: String? = nil, + exclude: [String] = [], + sources: [String]? = nil, + settings: [SwiftSetting]? = nil + ) -> CustomTarget { + CustomTarget( + kind: kind, + name: name, + dependencies: dependencies, + directory: directory ?? name, + exclude: exclude, + sources: sources, + settings: settings ?? (kind.isTest ? _testSettings : _settings)) + } + + func toTarget() -> Target { + var linkerSettings: [LinkerSetting] = [] + if kind == .testSupport { + linkerSettings.append( + .linkedFramework("XCTest", .when(platforms: [.macOS, .iOS, .watchOS, .tvOS]))) + } + switch kind { + case .exported, .hidden, .testSupport: + return Target.target( + name: name, + dependencies: dependencies, + path: kind.path(for: directory), + exclude: exclude, + sources: sources, + swiftSettings: settings, + linkerSettings: linkerSettings) + case .test: + return Target.testTarget( + name: name, + dependencies: dependencies, + path: kind.path(for: directory), + exclude: exclude, + swiftSettings: settings, + linkerSettings: linkerSettings) + } + } +} + +let targets: [CustomTarget] = [ + .target( + kind: .testSupport, + name: "_CollectionsTestSupport", + dependencies: [ + "InternalCollectionsUtilities", + "ContainersPreview", + "BasicContainers", + "SpanPreview", + ]), + .target( + kind: .test, + name: "CollectionsTestSupportTests", + dependencies: ["_CollectionsTestSupport"]), + .target( + kind: .hidden, + name: "InternalCollectionsUtilities", + exclude: [ + "CMakeLists.txt", + ]), + + .target( + kind: .exported, + name: "BasicContainers", + dependencies: ["InternalCollectionsUtilities", "SpanPreview"], + exclude: ["CMakeLists.txt"] + ), + .target( + kind: .test, + name: "BasicContainersTests", + dependencies: [ + "BasicContainers", "_CollectionsTestSupport" + ]), + + .target( + kind: .exported, + name: "BitCollections", + dependencies: ["InternalCollectionsUtilities"], + exclude: ["CMakeLists.txt"]), + .target( + kind: .test, + name: "BitCollectionsTests", + dependencies: [ + "BitCollections", "_CollectionsTestSupport", "OrderedCollections" + ]), + + .target( + kind: .exported, + name: "ContainersPreview", + dependencies: [ + "InternalCollectionsUtilities", + "BasicContainers", + "DequeModule", + "SpanPreview", + ], + exclude: ["CMakeLists.txt"]), + .target( + kind: .test, + name: "ContainersTests", + dependencies: [ + "ContainersPreview", "_CollectionsTestSupport" + ]), + + .target( + kind: .exported, + name: "DequeModule", + dependencies: ["InternalCollectionsUtilities", "SpanPreview"], + exclude: ["CMakeLists.txt"]), + .target( + kind: .test, + name: "DequeTests", + dependencies: ["DequeModule", "_CollectionsTestSupport"]), + + .target( + kind: .exported, + name: "HashTreeCollections", + dependencies: ["InternalCollectionsUtilities"], + exclude: ["CMakeLists.txt"]), + .target( + kind: .test, + name: "HashTreeCollectionsTests", + dependencies: ["HashTreeCollections", "_CollectionsTestSupport"]), + + .target( + kind: .exported, + name: "HeapModule", + dependencies: ["InternalCollectionsUtilities"], + exclude: ["CMakeLists.txt"]), + .target( + kind: .test, + name: "HeapTests", + dependencies: ["HeapModule", "_CollectionsTestSupport"]), + + .target( + kind: .exported, + name: "OrderedCollections", + dependencies: ["InternalCollectionsUtilities"], + exclude: ["CMakeLists.txt"]), + .target( + kind: .test, + name: "OrderedCollectionsTests", + dependencies: ["OrderedCollections", "_CollectionsTestSupport"]), + + .target( + kind: .exported, + name: "_RopeModule", + dependencies: ["InternalCollectionsUtilities"], + directory: "RopeModule", + exclude: ["CMakeLists.txt"], + // FIXME: _modify accessors in RopeModule seem to be broken in Swift 6 mode + settings: _settings + [.swiftLanguageMode(.v5)]), + .target( + kind: .test, + name: "RopeModuleTests", + dependencies: ["_RopeModule", "_CollectionsTestSupport"]), + + .target( + kind: .exported, + name: "SpanPreview", + dependencies: ["InternalCollectionsUtilities"], + exclude: ["CMakeLists.txt"]), + .target( + kind: .test, + name: "SpanPreviewTests", + dependencies: ["SpanPreview", "_CollectionsTestSupport"]), + + .target( + kind: .exported, + name: "TrailingElementsModule", + dependencies: ["InternalCollectionsUtilities"], + exclude: ["CMakeLists.txt"]), + .target( + kind: .test, + name: "TrailingElementsTests", + dependencies: ["TrailingElementsModule"]), + + .target( + kind: .exported, + name: "SortedCollections", + dependencies: ["InternalCollectionsUtilities"], + directory: "SortedCollections"), + .target( + kind: .test, + name: "SortedCollectionsTests", + dependencies: ["SortedCollections", "_CollectionsTestSupport"]), + + .target( + kind: .exported, + name: "Collections", + dependencies: [ + "BitCollections", + "DequeModule", + "HashTreeCollections", + "HeapModule", + "OrderedCollections", + "_RopeModule", + ], + exclude: ["CMakeLists.txt"]), + .target( + kind: .test, + name: "CollectionsModuleTests", + dependencies: ["Collections", "_CollectionsTestSupport"], + settings: _baseSettings + [.enableUpcomingFeature("MemberImportVisibility")]), +] + +let _products: [Product] = targets.compactMap { t in + guard t.kind == .exported else { return nil } + return .library(name: t.name, targets: [t.name]) +} +let _targets: [Target] = targets.map { $0.toTarget() } + +let package = Package( + name: "swift-collections", + products: _products, + traits: _traits, + targets: _targets) diff --git a/Sources/BasicContainers/RigidArray/RigidArray+ContainerOperations.swift b/Sources/BasicContainers/RigidArray/RigidArray+ContainerOperations.swift index 1c09a053..f6c346eb 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+ContainerOperations.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+ContainerOperations.swift @@ -141,11 +141,11 @@ extension RigidArray where Element: ~Copyable { public subscript(position: Int) -> Element { @inline(__always) unsafeAddress { - _ptr(to: position) + unsafe _ptr(to: position) } @inline(__always) unsafeMutableAddress { - _mutablePtr(to: position) + unsafe _mutablePtr(to: position) } } #endif diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+ContainerOperations.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+ContainerOperations.swift index efbf9f72..a68fe5d9 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+ContainerOperations.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+ContainerOperations.swift @@ -95,11 +95,11 @@ extension UniqueArray where Element: ~Copyable { public subscript(position: Int) -> Element { @inline(__always) unsafeAddress { - _storage._ptr(to: position) + unsafe _storage._ptr(to: position) } @inline(__always) unsafeMutableAddress { - _storage._mutablePtr(to: position) + unsafe _storage._mutablePtr(to: position) } } #endif diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque.swift index 0dca4fe1..806ab5d1 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque.swift @@ -215,15 +215,15 @@ extension UniqueDeque where Element: ~Copyable { @_transparent unsafeAddress { precondition(position >= 0 && position < count, "Index out of bounds") - let slot = _storage._handle.slot(forOffset: position) - return _storage._handle.ptr(at: slot) + let slot = unsafe _storage._handle.slot(forOffset: position) + return unsafe _storage._handle.ptr(at: slot) } @inline(__always) @_transparent unsafeMutableAddress { precondition(position >= 0 && position < count, "Index out of bounds") - let slot = _storage._handle.slot(forOffset: position) - return _storage._handle.mutablePtr(at: slot) + let slot = unsafe _storage._handle.slot(forOffset: position) + return unsafe _storage._handle.mutablePtr(at: slot) } } #endif diff --git a/Sources/InternalCollectionsUtilities/OutputSpan+Extras.swift b/Sources/InternalCollectionsUtilities/OutputSpan+Extras.swift index 69dc9712..70d21f42 100644 --- a/Sources/InternalCollectionsUtilities/OutputSpan+Extras.swift +++ b/Sources/InternalCollectionsUtilities/OutputSpan+Extras.swift @@ -18,7 +18,7 @@ package func withTemporaryOutputSpan capacity: Int, _ body: (inout OutputSpan) throws(E) -> R ) throws(E) -> R { - unsafe try _withUnsafeTemporaryAllocation( + try _withUnsafeTemporaryAllocation( of: Element.self, capacity: capacity ) { buffer throws(E) in var span = unsafe OutputSpan(buffer: buffer, initializedCount: 0) diff --git a/Sources/InternalCollectionsUtilities/TemporaryAllocation.swift b/Sources/InternalCollectionsUtilities/TemporaryAllocation.swift index 6cd82464..8d120506 100644 --- a/Sources/InternalCollectionsUtilities/TemporaryAllocation.swift +++ b/Sources/InternalCollectionsUtilities/TemporaryAllocation.swift @@ -13,6 +13,7 @@ /// A polyfill of the typed-throws supporting `withUnsafeTemporaryAllocation` in the 6.3 stdlib. @_alwaysEmitIntoClient @_transparent +@safe package func _withUnsafeTemporaryAllocation< T: ~Copyable, R: ~Copyable, E: Error @@ -21,14 +22,35 @@ package func _withUnsafeTemporaryAllocation< capacity: Int, _ body: (UnsafeMutableBufferPointer) throws(E) -> R ) throws(E) -> R { -#if compiler(>=6.3) +#if compiler(>=6.4) try withUnsafeTemporaryAllocation(of: type, capacity: capacity, body) #else - let r: Result = withUnsafeTemporaryAllocation( + let r: Result = unsafe withUnsafeTemporaryAllocation( of: T.self, capacity: capacity ) { buffer in - return Result(catching: { () throws(E) in try body(buffer) }) + return Result(catching: { () throws(E) in unsafe try body(buffer) }) } return try r.get() #endif } + +// FIXME: Remove when we drop Swift 6.2 +@_alwaysEmitIntoClient +@_transparent +@safe +package func _withUnsafeTemporaryAllocation( + byteCount: Int, + alignment: Int, + _ body: (UnsafeMutableRawBufferPointer) throws(E) -> R +) throws(E) -> R { +#if compiler(<6.3) + let r: Result = unsafe withUnsafeTemporaryAllocation( + byteCount: byteCount, alignment: alignment + ) { buffer in + return Result(catching: { () throws(E) in unsafe try body(buffer) }) + } + return try r.get() +#else + return try withUnsafeTemporaryAllocation(byteCount: byteCount, alignment: alignment, body) +#endif +} diff --git a/Sources/InternalCollectionsUtilities/UnsafeBitSet/_UnsafeBitSet.swift b/Sources/InternalCollectionsUtilities/UnsafeBitSet/_UnsafeBitSet.swift index faf6feff..ec4e6a71 100644 --- a/Sources/InternalCollectionsUtilities/UnsafeBitSet/_UnsafeBitSet.swift +++ b/Sources/InternalCollectionsUtilities/UnsafeBitSet/_UnsafeBitSet.swift @@ -118,7 +118,7 @@ extension _UnsafeBitSet { run body: (inout Self) throws -> Void ) rethrows { assert(wordCount >= 0) - return try withUnsafeTemporaryAllocation( + return try _withUnsafeTemporaryAllocation( of: _Word.self, capacity: wordCount ) { words in var bitset = unsafe Self(words: words, mutable: true) diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Move.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Move.swift index 888fea1c..f47f40b2 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Move.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Move.swift @@ -277,7 +277,7 @@ extension OrderedSet { // Elements that aren't members of the set are skipped. let handled: Void? = elements.withContiguousStorageIfAvailable { source in guard source.count > 0 else { return } - withUnsafeTemporaryAllocation( + _withUnsafeTemporaryAllocation( of: Int.self, capacity: source.count ) { sourceOffsets in var isContiguousRange = true @@ -376,7 +376,7 @@ extension OrderedSet { to: target, applyingTo: body) } else { - withUnsafeTemporaryAllocation(of: Int.self, capacity: c) { sortedBuffer in + _withUnsafeTemporaryAllocation(of: Int.self, capacity: c) { sortedBuffer in unsafe sortedBuffer.baseAddress!.initialize( from: sourceOffsets.baseAddress!, count: c) var sorted = unsafe sortedBuffer @@ -621,7 +621,7 @@ extension UnsafeMutableBufferPointer { if unsafe sortedSources[c - 1] - minSource == c - 1 { // Contiguous indices in a different order: rotate, then permute. unsafe _moveSubrange(minSource ..< minSource + c, toOffset: destination) - withUnsafeTemporaryAllocation(of: Int.self, capacity: c) { perm in + _withUnsafeTemporaryAllocation(of: Int.self, capacity: c) { perm in for i in 0 ..< c { unsafe perm[i] = sourceOffsets[i] - minSource } @@ -684,7 +684,7 @@ extension UnsafeMutableBufferPointer { totalCount: Int ) { let count = sourceOffsets.count - withUnsafeTemporaryAllocation( + _withUnsafeTemporaryAllocation( of: Element.self, capacity: count ) { saved in for i in 0 ..< count { diff --git a/Sources/SortedCollections/BTree/_Node.UnsafeHandle+CustomDebugStringConvertible.swift b/Sources/SortedCollections/BTree/_Node.UnsafeHandle+CustomDebugStringConvertible.swift index 1c042036..bfa2d800 100644 --- a/Sources/SortedCollections/BTree/_Node.UnsafeHandle+CustomDebugStringConvertible.swift +++ b/Sources/SortedCollections/BTree/_Node.UnsafeHandle+CustomDebugStringConvertible.swift @@ -125,7 +125,7 @@ extension _Node.UnsafeHandle: CustomDebugStringConvertible { public var debugDescription: String { var result = "Node<\(Key.self), \(Value.self)>([" var first = true - for slot in 0..) throws(E) -> R ) throws(E) -> R { - unsafe try _withUnsafeTemporaryAllocation( + try _withUnsafeTemporaryAllocation( of: Element.self, capacity: capacity ) { buffer throws(E) in var span = unsafe InputSpan(buffer: buffer, initializedCount: 0) diff --git a/Sources/TrailingElementsModule/CMakeLists.txt b/Sources/TrailingElementsModule/CMakeLists.txt index eeb2a127..b04a3625 100644 --- a/Sources/TrailingElementsModule/CMakeLists.txt +++ b/Sources/TrailingElementsModule/CMakeLists.txt @@ -14,6 +14,8 @@ if(COLLECTIONS_SINGLE_MODULE) else() set(module_name TrailingElementsModule) add_library(TrailingElementsModule) + target_link_libraries(TrailingElementsModule PRIVATE + InternalCollectionsUtilities) set_target_properties(TrailingElementsModule PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY}) diff --git a/Sources/TrailingElementsModule/TrailingArray.swift b/Sources/TrailingElementsModule/TrailingArray.swift index c5ff7982..53a840f6 100644 --- a/Sources/TrailingElementsModule/TrailingArray.swift +++ b/Sources/TrailingElementsModule/TrailingArray.swift @@ -11,6 +11,10 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + /// A value that manages a contiguous block of memory starting with a header /// value and then followed by a contiguous array of elements. Values of this /// type own the underlying memory, and are non-copyable to ensure that @@ -354,39 +358,33 @@ extension TrailingArray { let (numBytes, alignment) = allocationSize(header: header) // Allocate temporary storage large enough for the value we need. - let result: Result = withUnsafeTemporaryAllocation( + return try _withUnsafeTemporaryAllocation( byteCount: numBytes, alignment: alignment - ) { buffer in + ) { buffer throws(E) in // Initialize the header within the temporary allocation. let storagePointer = buffer.baseAddress! let headerPointer = unsafe TrailingArray.headerPointer(fromStorage: storagePointer) unsafe headerPointer.initialize(to: header) /// Create a trailing array over that temporary storage. - var managedBuffer = unsafe TrailingArray( + var managedBuffer: Optional = unsafe TrailingArray( consuming: headerPointer, storage: storagePointer) - let resultOrError: Result - do throws(E) { - resultOrError = .success(try body(&managedBuffer)) - } catch { - resultOrError = .failure(error) + + defer { + let buffer = managedBuffer.take()! + // Deinitialize the elements and header. + unsafe buffer.rawElements.deinitialize() + unsafe buffer._pointer.deinitialize(count: 1) + + // Tell the trailing buffer not to free the storage. + let (finalPointer, finalStorage) = unsafe buffer.leakStorage() + precondition(unsafe finalPointer == headerPointer) + precondition(unsafe finalStorage == storagePointer) } - - // Deinitialize the elements and header. - unsafe managedBuffer.rawElements.deinitialize() - unsafe managedBuffer._pointer.deinitialize(count: 1) - - // Tell the trailing buffer not to free the storage. - let (finalPointer, finalStorage) = unsafe managedBuffer.leakStorage() - precondition(unsafe finalPointer == headerPointer) - precondition(unsafe finalStorage == storagePointer) - - return resultOrError + return try body(&managedBuffer!) } - - return try result.get() } } diff --git a/Sources/TrailingElementsModule/TrailingPadding.swift b/Sources/TrailingElementsModule/TrailingPadding.swift index 2aedf46f..dc8e1440 100644 --- a/Sources/TrailingElementsModule/TrailingPadding.swift +++ b/Sources/TrailingElementsModule/TrailingPadding.swift @@ -11,6 +11,10 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + /// Represents memory containing a header value followed by some extra padding /// following it. Values of this type own the underlying memory, and are /// non-copyable to ensure that ownership of that memory is unique. Memory @@ -116,32 +120,21 @@ extension TrailingPadding where Header: Copyable { "must allocate enough storage for the underlying stored type") // Allocate temporary storage large enough for the value we need. - let result: Result = withUnsafeTemporaryAllocation( + return try _withUnsafeTemporaryAllocation( byteCount: size, alignment: MemoryLayout
.alignment - ) { buffer in + ) { buffer throws(E) in /// Create a tail-allocated storage over that temporary storage. let pointer = unsafe buffer.baseAddress!.assumingMemoryBound(to: Header.self) unsafe pointer.initialize(to: header) - var tailAllocated = unsafe TrailingPadding(consuming: pointer) - - do throws(E) { - let result = try body(&tailAllocated) - + var tailAllocated: Optional = unsafe TrailingPadding(consuming: pointer) + defer { + let tailAllocated = tailAllocated.take()! // Tell the tail-allocated buffer not to free the storage. let finalPointer = unsafe tailAllocated.leakStorage() precondition(unsafe finalPointer == pointer) - - return .success(result) - } catch { - // Tell the tail-allocated buffer not to free the storage. - let finalPointer = unsafe tailAllocated.leakStorage() - precondition(unsafe finalPointer == pointer) - - return .failure(error) } + return try body(&tailAllocated!) } - - return try result.get() } }