Skip to content

Commit 6bd96b1

Browse files
authored
Improvements to ThreadSafeBox (#6296)
- Offer a mutate function - Offer an append function for boxed strings
1 parent 111093f commit 6bd96b1

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

Sources/Basics/Concurrency/ThreadSafeBox.swift

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,13 @@ public final class ThreadSafeBox<Value> {
2424
self.underlying = seed
2525
}
2626

27+
public func mutate(body: (Value?) throws -> Value?) rethrows {
28+
try self.lock.withLock {
29+
let value = try body(self.underlying)
30+
self.underlying = value
31+
}
32+
}
33+
2734
@discardableResult
2835
public func memoize(body: () throws -> Value) rethrows -> Value {
2936
if let value = self.get() {
@@ -100,4 +107,16 @@ extension ThreadSafeBox where Value == Int {
100107
}
101108
}
102109

110+
extension ThreadSafeBox where Value == String {
111+
public func append(_ value: String) {
112+
self.mutate { existingValue in
113+
if let existingValue {
114+
return existingValue + value
115+
} else {
116+
return value
117+
}
118+
}
119+
}
120+
}
121+
103122
extension ThreadSafeBox: @unchecked Sendable where Value: Sendable {}

0 commit comments

Comments
 (0)