-
Notifications
You must be signed in to change notification settings - Fork 10.8k
Expand file tree
/
Copy pathLocking.swift
More file actions
64 lines (52 loc) · 1.98 KB
/
Copy pathLocking.swift
File metadata and controls
64 lines (52 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2023 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
//
//===----------------------------------------------------------------------===//
@_silgen_name("_swift_observation_lock_size")
func _lockSize() -> Int
@_silgen_name("_swift_observation_lock_init")
func _lockInit(_: UnsafeRawPointer)
@_silgen_name("_swift_observation_lock_lock")
func _lockLock(_: UnsafeRawPointer)
@_silgen_name("_swift_observation_lock_unlock")
func _lockUnlock(_: UnsafeRawPointer)
@available(SwiftStdlib 5.9, *)
internal struct _ManagedCriticalState<State> {
final private class LockedBuffer: ManagedBuffer<State, UnsafeRawPointer> { }
private let buffer: ManagedBuffer<State, UnsafeRawPointer>
internal init(_ buffer: ManagedBuffer<State, UnsafeRawPointer>) {
self.buffer = buffer
}
internal init(_ initial: State) {
let roundedSize = (_lockSize() + MemoryLayout<UnsafeRawPointer>.size - 1) / MemoryLayout<UnsafeRawPointer>.size
self.init(LockedBuffer.create(minimumCapacity: Swift.max(roundedSize, 1)) { buffer in
buffer.withUnsafeMutablePointerToElements { _lockInit(UnsafeRawPointer($0)) }
return initial
})
}
internal func withCriticalRegion<R>(
_ critical: (inout State) throws -> R
) rethrows -> R {
try buffer.withUnsafeMutablePointers { header, lock in
_lockLock(UnsafeRawPointer(lock))
defer {
_lockUnlock(UnsafeRawPointer(lock))
}
return try critical(&header.pointee)
}
}
}
@available(SwiftStdlib 5.9, *)
extension _ManagedCriticalState: @unchecked Sendable where State: Sendable { }
@available(SwiftStdlib 5.9, *)
extension _ManagedCriticalState: Identifiable {
internal var id: ObjectIdentifier {
ObjectIdentifier(buffer)
}
}