FIRAllocatedUnfairLock.swift 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright 2025 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import Foundation
  15. import os.lock
  16. /// A reference wrapper around `os_unfair_lock`. Replace this class with
  17. /// `OSAllocatedUnfairLock` once we support only iOS 16+. For an explanation
  18. /// on why this is necessary, see the docs:
  19. /// https://developer.apple.com/documentation/os/osallocatedunfairlock
  20. public final class FIRAllocatedUnfairLock<State>: @unchecked Sendable {
  21. private var lockPointer: UnsafeMutablePointer<os_unfair_lock>
  22. private var state: State
  23. public init(initialState: sending State) {
  24. lockPointer = UnsafeMutablePointer<os_unfair_lock>
  25. .allocate(capacity: 1)
  26. lockPointer.initialize(to: os_unfair_lock())
  27. state = initialState
  28. }
  29. public convenience init() where State == Void {
  30. self.init(initialState: ())
  31. }
  32. public func lock() {
  33. os_unfair_lock_lock(lockPointer)
  34. }
  35. public func unlock() {
  36. os_unfair_lock_unlock(lockPointer)
  37. }
  38. @discardableResult
  39. public func withLock<R>(_ body: (inout State) throws -> R) rethrows -> R {
  40. let value: R
  41. lock()
  42. defer { unlock() }
  43. value = try body(&state)
  44. return value
  45. }
  46. @discardableResult
  47. public func withLock<R>(_ body: () throws -> R) rethrows -> R {
  48. let value: R
  49. lock()
  50. defer { unlock() }
  51. value = try body()
  52. return value
  53. }
  54. deinit {
  55. lockPointer.deallocate()
  56. }
  57. }
  58. // This class is used to get around a limitation where local variables cannot be
  59. // declared nonisolated for things like capture and mutation in escaping closures.
  60. public final class FIRNonisolatedUnsafe<State>: @unchecked Sendable {
  61. public private(set) var state: State
  62. public init(initialState: State) {
  63. state = initialState
  64. }
  65. @discardableResult
  66. public func withNonisolatedUnsafeState<R>(_ body: (inout State) throws -> R) rethrows -> R {
  67. let value: R
  68. value = try body(&state)
  69. return value
  70. }
  71. }