Skip to content

Commit 223ee80

Browse files
authored
Merge pull request #242 from keith/ks/make-rule-namecache-thread-safe
Make Rule nameCache thread safe
2 parents be4a5a0 + 17e770c commit 223ee80

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

Sources/SwiftFormatCore/Rule.swift

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
//
1111
//===----------------------------------------------------------------------===//
1212

13+
import Foundation
14+
1315
/// A Rule is a linting or formatting pass that executes in a given context.
1416
public protocol Rule {
1517
/// The context in which the rule is executed.
@@ -26,16 +28,26 @@ public protocol Rule {
2628
}
2729

2830
fileprivate var nameCache = [ObjectIdentifier: String]()
31+
fileprivate var nameCacheQueue = DispatchQueue(
32+
label: "com.apple.SwiftFormat.NameCache", attributes: .concurrent)
2933

3034
extension Rule {
3135
/// By default, the `ruleName` is just the name of the implementing rule class.
3236
public static var ruleName: String {
3337
let identifier = ObjectIdentifier(self)
34-
if let cachedName = nameCache[identifier] {
38+
let cachedName = nameCacheQueue.sync {
39+
nameCache[identifier]
40+
}
41+
42+
if let cachedName = cachedName {
3543
return cachedName
3644
}
45+
3746
let name = String("\(self)".split(separator: ".").last!)
38-
nameCache[identifier] = name
47+
nameCacheQueue.async(flags: .barrier) {
48+
nameCache[identifier] = name
49+
}
50+
3951
return name
4052
}
4153
}

0 commit comments

Comments
 (0)