|
9 | 9 | */
|
10 | 10 |
|
11 | 11 | import Foundation
|
| 12 | +import TSCLibc |
12 | 13 |
|
13 | 14 | /// This class bridges the gap between Darwin and Linux Foundation Threading API.
|
14 | 15 | /// It provides closure based execution and a join method to block the calling thread
|
@@ -86,17 +87,59 @@ final private class ThreadImpl: Foundation.Thread {
|
86 | 87 | typealias ThreadImpl = Foundation.Thread
|
87 | 88 | #endif
|
88 | 89 |
|
| 90 | +protocol Defaultable { |
| 91 | + static var defaultValue: Self { get } |
| 92 | +} |
| 93 | + |
| 94 | +extension Optional: Defaultable { |
| 95 | + static var defaultValue: Optional<Wrapped> { .none } |
| 96 | +} |
| 97 | + |
89 | 98 | /// `ThreadLocal` properties are thread-specific. Every thread has its own instance of the wrapped property.
|
90 |
| -@propertyWrapper struct ThreadLocal<Value> { |
| 99 | +@propertyWrapper final class ThreadLocal<Value: Defaultable> { |
91 | 100 | private var storage: NSMutableDictionary { ThreadImpl.current.threadDictionary }
|
92 | 101 | private let key = UUID().uuidString
|
93 | 102 |
|
94 |
| - var wrappedValue: Value? { |
95 |
| - get { storage[key] as? Value } |
| 103 | + var wrappedValue: Value { |
| 104 | + get { |
| 105 | + if let value = storage[key] as? Value { |
| 106 | + return value |
| 107 | + } else { |
| 108 | + let value = Value.defaultValue |
| 109 | + storage[key] = value |
| 110 | + return value |
| 111 | + } |
| 112 | + } |
96 | 113 | set { storage[key] = newValue }
|
97 | 114 | }
|
98 | 115 |
|
99 |
| - init(wrappedValue: Value?) { |
| 116 | + init(wrappedValue: Value) { |
| 117 | + self.wrappedValue = wrappedValue |
| 118 | + } |
| 119 | +} |
| 120 | + |
| 121 | +/// Automatically closes the wrapped file descriptor on deinit. |
| 122 | +@propertyWrapper final class AutoClosing: NSObject, Defaultable { |
| 123 | + #if os(Windows) |
| 124 | + typealias T = HANDLE |
| 125 | + #else |
| 126 | + typealias T = CInt |
| 127 | + #endif |
| 128 | + var wrappedValue: T? |
| 129 | + |
| 130 | + static var defaultValue: AutoClosing { AutoClosing(wrappedValue: .none) } |
| 131 | + |
| 132 | + init(wrappedValue: T?) { |
100 | 133 | self.wrappedValue = wrappedValue
|
101 | 134 | }
|
| 135 | + |
| 136 | + deinit { |
| 137 | + if let wrappedValue = wrappedValue { |
| 138 | + #if os(Windows) |
| 139 | + CloseHandle(wrappedValue) |
| 140 | + #else |
| 141 | + close(wrappedValue) |
| 142 | + #endif |
| 143 | + } |
| 144 | + } |
102 | 145 | }
|
0 commit comments