mirror of
https://github.com/apple/swift-foundation.git
synced 2025-05-18 19:22:35 +08:00
* Revert "Create FoundationInternals, an internal module to host shared files used by FoundationInternationalization and FoundationEssentials (#101)" This reverts commit 8f08a649db1f3eb31593cdae7a30c5e95cb614a7. * Reapply fb718cd3fb9f058a5fd6d736cec9c2b99d6f7dc6 fix to the other restored LockedState
46 lines
1.3 KiB
Swift
46 lines
1.3 KiB
Swift
//===----------------------------------------------------------------------===//
|
|
//
|
|
// This source file is part of the Swift.org open source project
|
|
//
|
|
// Copyright (c) 2014 - 2022 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
|
|
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
|
//
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
struct RegexPatternCache: @unchecked Sendable {
|
|
private struct Key : Sendable, Hashable {
|
|
var pattern: String
|
|
var caseInsensitive: Bool
|
|
}
|
|
|
|
private let _lock: LockedState<[Key: Regex<AnyRegexOutput>]>
|
|
|
|
static let cache = RegexPatternCache()
|
|
|
|
fileprivate init() {
|
|
_lock = LockedState(initialState: .init())
|
|
}
|
|
|
|
func regex(for pattern: String, caseInsensitive: Bool) throws -> Regex<AnyRegexOutput>? {
|
|
|
|
let key = Key(pattern: pattern, caseInsensitive: caseInsensitive)
|
|
|
|
return try _lock.withLock { cache in
|
|
|
|
if let cached = cache[key] {
|
|
return cached
|
|
}
|
|
|
|
var r = try Regex(pattern)
|
|
if caseInsensitive {
|
|
r = r.ignoresCase()
|
|
}
|
|
cache[key] = r
|
|
return r
|
|
}
|
|
}
|
|
}
|