Skip to content

Commit 2ead1c9

Browse files
add static create function where Element is noncopyable
1 parent 5bae1f5 commit 2ead1c9

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Sources/VariableLengthArray/VLArray.swift

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,7 @@ public struct VLArray<Element>: ~Copyable, @unchecked Sendable where Element: ~C
112112
}
113113

114114
// MARK: Subscript
115+
// copyable
115116
extension VLArray {
116117
/// Accesses the element at the specified position.
117118
///
@@ -144,6 +145,8 @@ extension VLArray {
144145
set { _storage[i] = newValue }
145146
}
146147
}
148+
149+
// noncopyable
147150
extension VLArray where Element: ~Copyable {
148151
/// Accesses the element at the specified position.
149152
///
@@ -178,6 +181,7 @@ extension VLArray where Element: ~Copyable {
178181
}
179182

180183
// MARK: Create
184+
// copyable
181185
extension VLArray {
182186
@inlinable
183187
public static func create<E: Error>(
@@ -213,6 +217,29 @@ extension VLArray {
213217
})
214218
}
215219
}
220+
221+
// noncopyable
222+
extension VLArray where Element: ~Copyable {
223+
@inlinable
224+
public static func create<E: Error>(
225+
amount: Int,
226+
initialize: (Index) -> Element,
227+
_ closure: (consuming Self) throws(E) -> Void
228+
) rethrows {
229+
try withUnsafeTemporaryAllocation(of: Element.self, capacity: amount, { p in
230+
for i in 0..<amount {
231+
p[i] = initialize(i)
232+
}
233+
defer {
234+
p.deinitialize()
235+
}
236+
let array = Self(_storage: p)
237+
try closure(array)
238+
})
239+
}
240+
}
241+
242+
// other
216243
extension VLArray where Element == UInt8 {
217244

218245
@inlinable

0 commit comments

Comments
 (0)